Generische Spezialisierung?
-
Hi,
im XNA-Framework seh ich oft sowas:
bla1 = content.Load<Audio> ("mysound"); bla2 = content.Load<Texture3d> ("mytexture"); bla3 = content.Load<Mesh> ("mymesh");
Da ja all diese Komponenten anders geladen werden, muss es ja eine Spezialisierung, bei den Methoden, geben.
Ich wollte jetzt selbst mal sowas probieren, doch das will nicht.
class xyz { public static T DoSomething<T> () where T : System.String { return (new string ("hallo")); } public static T DoSomething<T> () where T : System.Int32 { return (44); } }
Hat jemand eine Idee wie man sowas realisieren kann?
-
C#'ler schrieb:
Ich wollte jetzt selbst mal sowas probieren, doch das will nicht.
Wenn du dir die Fehlermeldung des Compilers zu deinem Beispiel genauer angesehen hättest wüsstest du, warum es nicht geht.
'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
Sowohl Systen.String als auch System.Int32 sind 'sealed' können also nicht so verwendet werden.
-
Eventuell hilft Dir das weiter:
namespace ConsoleApplication1 { class testa { public T foo<T>(T x) { Console.WriteLine(x.ToString()); return x; } public string foo<T>(string x) { Console.WriteLine("Spezialisierung:" + x); return x; } } class Program { static void Main(string[] args) { testa ta = new testa(); ta.foo<int>(12); ta.foo<string>("Hallo Welt"); } } }