简体   繁体   English

C#动态绑定和void方法调用

[英]C# dynamic binding and void method call

Why does the compiler let this expression to compile while the run-time exception is inevitable? 为什么编译器在运行时异常不可避免的情况下让这个表达式编译?

I don't think that the Dynamic Binding should work for void methods 我不认为Dynamic Binding应该适用于void方法

static void Main(string[] args)
{
    var res = Test((dynamic)"test");  // throws RuntimeBinderException exception at runtime
}

static void Test(dynamic args)
{
}

If the C# spec is referring the above expression as dynamically bound expression why doesn't the following method compile? 如果C#规范将上面的表达式称为动态绑定表达式,为什么以下方法不能编译?

static dynamic DynamicMethod()
{
}

Test((dynamic)"abc") is evaluated in its entirety as a dynamic statement. 测试((动态)“abc”)作为动态语句全部评估。 More completely, you could have: 更完整的是,您可以:

public static string Test(string s) { return s; }

This would be a better overload, so would be selected and executed in preference to the other method. 这将是一个更好的重载,因此将优先于其他方法选择和执行。

Or in other words: it can't know whether the return is void without resolving the method-group to a particular signature. 或者换句话说:如果不将方法组解析为特定签名,它就无法知道返回是否为空。 And overload resolution is by definition deferred until runtime for a dynamic invoke. 根据定义 ,重载决策被推迟到动态调用的运行时。

Could it do more analysis? 它可以做更多分析吗? Probably. 大概。 But the specification does not require it to, so at the absolute most it could be a warning (not an error). 但规范并不要求它,所以最绝对的可能是警告(而不是错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM