为什么更多主流的静态类型语言不支持返回类型的函数/方法重载?我想不出那样做.通过参数类型支持过载似乎没有那么有用或合理.怎么这么不受欢迎呢?
programming-languages overloading language-design function-calls
在方法重载中,是否可以为重载方法设置不同的返回类型?例如,
void foo(int x) ;
int foo(int x,int y);
double foo(String str);
Run Code Online (Sandbox Code Playgroud)
在一般的面向对象编程中,有可能吗?
在C#中,我需要能够定义一个方法,但让它返回一个或两个返回类型.我尝试这样做时编译器给出了一个错误,但为什么不知道我需要调用哪种方法呢?
int x = FunctionReturnsIntOrString();
Run Code Online (Sandbox Code Playgroud)
为什么编译器会阻止我使用具有不同返回类型的两个函数?
为什么这两种方法不能同名?是因为 C# 编译器在重载时没有考虑泛型类型约束吗?它可以在 C# 的未来版本中完成吗?
public static TValue GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : class
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return null;
}
public static TValue? GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : struct
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return null;
}
Run Code Online (Sandbox Code Playgroud)