为什么c#编译器不检查“静态性”的方法在调用站点与动态参数? [英] Why doesn't the c# compiler check "staticness" of the method at call sites with a dynamic argument?
问题描述
为什么C#编译器不告诉我这段代码是无效的?
Why doesn't the C# compiler tell me that this piece of code is invalid?
class Program
{
static void Main(string[] args)
{
dynamic d = 1;
MyMethod(d);
}
public void MyMethod(int i)
{
Console.WriteLine("int");
}
}
调用 MyMethod
在运行时失败,因为我试图从静态方法调用非静态方法。这是非常合理的,但为什么编译器认为这在编译时是错误?
The call to MyMethod
fails at runtime because I am trying to call a non-static method from a static method. That is very reasonable, but why doesn't the compiler consider this an error at compile time?
以下将不编译
class Program
{
static void Main(string[] args)
{
dynamic d = 1;
MyMethod(d);
}
}
因此尽管动态分派,编译器会检查 MyMethod
存在。为什么不验证静态?
so despite the dynamic dispatch, the compiler does check that MyMethod
exists. Why doesn't it verify the "staticness"?
推荐答案
过载分辨率是动态的。在此代码段中可见:
Overload resolution is dynamic here. Visible in this code snippet:
class Program {
public static void Main() {
dynamic d = 1.0;
MyMethod(d);
}
public void MyMethod(int i) {
Console.WriteLine("int");
}
public static void MyMethod(double d) {
Console.WriteLine("double");
}
}
现在将1分配给d,并记下运行时故障。编译器在编译时不能合理地模拟动态重载解析,所以不会尝试。
Works fine. Now assign 1 to d and note the runtime failure. The compiler cannot reasonably emulate dynamic overload resolution at compile time, so it doesn't try.
这篇关于为什么c#编译器不检查“静态性”的方法在调用站点与动态参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!