[英]Why does c# compiler allow incorrect match of return value type and variable type?
Consider the following code: 请考虑以下代码:
static void Main()
{
dynamic a = 1;
int b = OneMethod(a);
}
private static string OneMethod(int number)
{
return "";
}
Please notice that type of b
and return type of OneMethod
does not match. 请注意,
return type of OneMethod
type of b
和return type of OneMethod
不匹配。 Nevertheless it builds and throws the exception at runtime. 然而,它在运行时构建并抛出异常。
My question is that why does the compiler let this?
我的问题是为什么编译器会这么做?
Or what is the philosophy behind this?
或者这背后的哲学是什么?
The reason behind this may be Compiler does not know which OneMethod would be called, because a is dynamic.
这背后的原因可能是
Compiler does not know which OneMethod would be called, because a is dynamic.
But why it cannot see that there is only one OneMethod
. 但为什么它看不到只有一个
OneMethod
。 There will surely be an exception at runtime. 运行时肯定会有异常。
Any expression that has an operand of type dynamic will have a type of dynamic itself. 任何具有dynamic类型操作数的表达式都将具有动态类型。
Thus your expression OneMethod(a)
returns an object that's typed dynamically 因此,表达式
OneMethod(a)
返回一个动态键入的对象
so the first part of your code is equivalent to 所以你的代码的第一部分相当于
static void Main()
{
dynamic a = 1;
dynamic temp = OneMethod(a);
int b = temp;
}
one way of argue why this is sensible even in your case depends on whether or not you think the compiler should change behavior for that particular line depending when you add the below method 有一种方法可以证明为什么即使在你的情况下这是明智的,取决于你是否认为编译器应该改变该特定行的行为,这取决于你添加下面的方法
private static T OneMethod<T>(T number)
Now the compiler won't know the type returned until runtime. 现在编译器将不知道在运行时返回的类型。 It won't even know which method is called.
它甚至不知道调用哪种方法。 The generic or the non generic.
通用或非通用。 Wouldn't you be surprised if it in the first case marked the assignment as a compile error and then by adding a completely different method it got moved to a runtime error?
如果它在第一种情况下将赋值标记为编译错误然后通过添加完全不同的方法将其移动到运行时错误,您不会感到惊讶吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.