无法在C#中重载的返回类型

时间:2015-10-11 10:48:14

标签: c#

为什么不能用Ienumerator这样的返回类型重载函数?

这种类型的处理方式与允许函数重载的其他类型的处理方式不同吗?

2 个答案:

答案 0 :(得分:1)

解决重载方法时不考虑返回类型。 IEnumerator没有什么特别之处。整个类型系统都是一样的。如果要从一个方法返回不同的类型,则需要声明基类或接口并返回该类型的实例。之后,您可以检查对象的实际类型,转换它并执行特定操作。

public interface IFoo
{
}

public class Bar : IFoo
{
    public void BarMethod() {}
}

public class Biz : IFoo
{
    public void BizMethod() {}
}

在其他地方,您可以声明这样的方法:

public class C
{
    public IFoo M(int i)
    {
        return (i == 0) ? new Bar() : new Biz();
    }
}

用法:

C c = new C();
var foo = c.M(1);
var barFoo = foo as Bar;
if (barFoo != null)
{
    barFoo.BarMethod();
}
else
{
    var bizFoo = foo as Biz;
    if (bizFoo != null)
    {
        bizFoo.BizMethod();
    }
}

答案 1 :(得分:-1)

为什么它没有意义的简单例子。

var class Demo
{
    public int GetValue()
    {
        return 3;
    }

    public string GetValue()
    {
        return "3";
    }
}

和用法

void Main(){
  var demo = new Demo();
  var thing = demo.GetValue();
}

编译器不知道你想要哪个GetValue()。

即使你说它的类型如

void Main(){
  var demo = new Demo();
  string thing = demo.GetValue();
}

这不是一个好的编码实践,会使你使用“var”无效。 暗示具有相同名称的方法可以返回两种不同的类型,这意味着代码的意图不明确。

即。在一个例子中它是“this”而另一个是它的“那个”。

相关问题