我想知道以下是否可能。创建一个接受匿名类型(string、int、decimal、customObject 等)的类,然后具有基于 Type 执行不同操作的重载方法。例子
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();
这是可能的还是我只是在做梦?