方法重载返回值 [英] Method overloading return values

查看:123
本文介绍了方法重载返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#我需要能够以定义的方法,但有它返回一个或两个返回类型。编译器给我一个错误,当我尝试这样做,但为什么是不是足够聪明,知道我需要调用哪个方法?

In C# I need to be able to define a method but have it return one or two return types. The compiler gives me an error when I try to do it, but why isn't it smart enough to know which method I need to call?

int x = FunctionReturnsIntOrString();



为什么会编译器阻止我具有不同的返回类型两个功能?

Why would the compiler prevent me from having two functions with different return types?

推荐答案

虽然它可能在此特定情形是显而易见的,有许多情形,其中,这是实际上不明显。让我们下面的API为例

While it may be obvious in this particular scenario, there are many scenarios where this is in fact not obvious. Lets take the following API for an example

class Bar { 
  public static int Foo();
  public static string Foo();
}



这是根本不可能的编译器知道在下面要调用哪个富场景

It's simply not possible for the compiler to know which Foo to call in the following scenarios

void Ambiguous() {
  Bar.Foo();
  object o = Bar.Foo();
  Dog d = (Dog)(Bar.Foo());
  var x = Bar.Foo();
  Console.WriteLine(Bar.Foo());
}



这些只是几个简单的样本。肯定存在更多的做作和邪恶的问题。

These are just a few quick samples. More contrived and evil problems surely exist.

这篇关于方法重载返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆