考虑以下代码:
static void Main()
{
dynamic a = 1;
int b = OneMethod(a);
}
private static string OneMethod(int number)
{
return "";
}
请注意,
type of b
和return type of OneMethod
不匹配。但是,它会在运行时生成并引发异常。我的问题是,为什么编译器允许这样做?或这背后的哲学是什么?其背后的原因可能是
Compiler does not know which OneMethod would be called, because a is dynamic.
,但是为什么看不到只有一个OneMethod
。在运行时肯定会有异常(exception)。 最佳答案
具有动态类型操作数的任何表达式本身都将具有动态类型。
因此,您的表达式OneMethod(a)
返回一个动态输入的对象
所以您的代码的第一部分相当于
static void Main()
{
dynamic a = 1;
dynamic temp = OneMethod(a);
int b = temp;
}
一种为什么即使在您的情况下也是明智的辩解方法取决于您是否认为编译器应根据添加以下方法的时间来更改特定行的行为
private static T OneMethod<T>(T number)
现在,编译器直到运行时才知道返回的类型。它甚至不知道调用哪个方法。通用或非通用。如果在第一种情况下将分配标记为编译错误,然后通过添加完全不同的方法将其转移到运行时错误,您会不会感到惊讶?