我确信对于有经验的程序员来说这是一个简单的问题,但我以前从来没有这样做过 - 假设我有一个自定义对象,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以,在我的代码中,我可以写如下内容:
MyClass FakeClass = new MyClass();
Dictionary<string,int> MyDict1 = FakeClass.ToDictInt();
Dictionary<string,string> MyDict2 = FakeClass.ToDictString();
Run Code Online (Sandbox Code Playgroud)
这工作得很好,但我希望能够做的是有一个方法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();
Run Code Online (Sandbox Code Playgroud)
所以,一个方法名称,但它根据要返回的变量知道要返回什么...如何在我的类中编写方法来执行此操作?
非常感谢!!