选择基于返回类型的调用结构

Joh*_*tos 2 c# methods class

我确信对于有经验的程序员来说这是一个简单的问题,但我以前从来没有这样做过 - 假设我有一个自定义对象,如下所示:

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)

所以,一个方法名称,但它根据要返回的变量知道要返回什么...如何在我的类中编写方法来执行此操作?

非常感谢!!

Ser*_*rvy 6

这是不可能的.重载决策算法不考虑方法调用表达式的上下文,因此在您提到的示例中会导致歧义错误.

对于具有不同返回类型的方法,您需要具有两个不同的方法名称(或参数列表中的差异).