【发布时间】:2014-04-30 17:42:06
【问题描述】:
我确信这对于有经验的程序员来说是一个简单的问题,但我以前从未这样做过 - 假设我有一个如下所示的自定义对象:
public class MyClass
{
public Dictionary<string,string> ToDictString()
{
Dictionary<string,string> retval = new Dictionary<string,string>;
// Whatever code
return retval;
}
public Dictionary<string,int> ToDictInt()
{
Dictionary<string,int> retval = new Dictionary<string,int>;
// Whatever code
return retval;
}
}
所以,在我的代码中,我可以写如下内容:
MyClass FakeClass = new MyClass();
Dictionary<string,int> MyDict1 = FakeClass.ToDictInt();
Dictionary<string,string> MyDict2 = FakeClass.ToDictString();
这很好用,但我想做的是在MyClass 中调用一个方法,比如ToDict(),可以根据预期的返回类型返回任一类型的字典
所以,例如,我会:
MyClass FakeClass = new MyClass();
// This would be the same as calling ToDictInt due to the return type:
Dictionary<string,int> MyDict1 = FakeClass.ToDict();
// This would be the same as calling ToDictString due to the return type:
Dictionary<string,string> MyDict2 = FakeClass.ToDict();
所以,一个方法名称,但它知道要根据要返回的变量返回什么...我将如何在我的类中编写方法来做到这一点?
非常感谢!!
【问题讨论】:
-
不可能像您描述的那样,但您可以定义一个通用方法并在每次调用时使用适当的类型,因此签名将是:
Dictionary<string, T> ToDict<T>()。这与您要求的有点不同,但可能值得一提。