我可以这样的东西:
int x = MyMethod<int>();
string y = MyMethod<string>();
Run Code Online (Sandbox Code Playgroud)
因此,一种方法基于T返回不同的类型.当然,方法中会有逻辑来确保它返回正确的东西.
我永远无法得到这样的东西来运行.它抱怨它无法将返回值强制转换为T:
public static T MyMethod<T>()
{
if(typeof(T) == typeof(Int32))
{
return 0;
}
else
{
return "nothing";
}
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*Par 10
请尝试以下方法
public static T MyMethod<T>() {
if ( typeof(T) == typeof(Int32) ) {
return (T)(object)0;
} else {
return (T)(object)"nothing";
}
}
Run Code Online (Sandbox Code Playgroud)
这里的诀窍是施法object.您尝试做的事情本质上是不安全的,因为编译器无法推断0或"无"可转换为任何给定的T.毕竟它是无限的.因此,只需明确地告诉编译器,转换为不安全object.
| 归档时间: |
|
| 查看次数: |
503 次 |
| 最近记录: |