Ich fragte mich, ob das Folgende möglich ist. Erstellen Sie eine Klasse, die einen anonymen Typ akzeptiert (string, int, dezimal, customObject usw.), und überladen Sie dann Methoden, die auf Grundlage des Typs verschiedene Operationen ausführen. BeispielMethode überladen mit Typen C#
class TestClass<T>
{
public void GetName<string>()
{
//do work knowing that the type is a string
}
public string GetName<int>()
{
//do work knowing that the type is an int
}
public string GetName<int>(int addNumber)
{
//do work knowing that the type is an int (overloaded)
}
public string GetName<DateTime>()
{
//do work knowing that the type is a DateTime
}
public string GetName<customObject>()
{
//do work knowing that the type is a customObject type
}
}
So, jetzt konnte ich die GetName-Methode aufrufen, und weil ich schon in der Art übergeben, wenn ich das Objekt initialisiert, wird die richtige Methode gefunden und ausgeführt.
TestClass foo = new TestClass<int>();
//executes the second method because that's the only one with a "int" type
foo.GetName();
Ist das möglich oder träume ich nur?
+1 Generics! = Vorlagen – user7116