我想知道以下是否可能。創建一個接受匿名類型(string,int,decimal,customObject等)的類,然後重載基於類型執行不同操作的方法。例如方法重載類型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
}
}
所以,現在我可以調用GetName方法,因爲我已經在類型過去了我初始化的對象,正確的方法是發現和執行。
TestClass foo = new TestClass<int>();
//executes the second method because that's the only one with a "int" type
foo.GetName();
這是可能的還是我只是在做夢?
+1 Generics!=模板 – user7116 2009-10-22 17:11:56