为什么这是编译时错误?
public TCastTo CastMe<TSource, TCastTo>(TSource i)
{
return (TCastTo)i;
}
Run Code Online (Sandbox Code Playgroud)
错误:
annot将类型'TSource'转换为'TCastTo'
为什么这是一个运行时错误?
public TCastTo CastMe<TSource, TCastTo>(TSource i)
{
return (TCastTo)(object)i;
}
int a = 4;
long b = CastMe<int, long>(a); // InvalidCastException
// this contrived example works
int aa = 4;
int bb = CastMe<int, int>(aa);
// this also works, the problem is limited to value types
string s = "foo";
object o = CastMe<string, object>(s);
Run Code Online (Sandbox Code Playgroud)
我搜索了SO和互联网以获得答案,并找到了类似的通用相关铸造问题的许多解释,但我找不到任何关于这个特殊的简单案例.
是否有某种方法可以将未知数字转换成双倍?例如
public static double Foo(object obj)
{
if (!obj.GetType().IsValueType)
throw new ArgumentException("Argument should be a number", "obj");
return (double) obj;
}
private static void Main(string[] args)
{
double dbl = 10;
decimal dec = 10;
int i = 10;
short s = 10;
Foo(dbl);
Foo(dec);
Foo(i);
Foo(s);
}
Run Code Online (Sandbox Code Playgroud)
但是当尝试将unbox打包为不正确的类型时,此代码会抛出异常.