Unboxing for dynamic type

十年热恋 提交于 2020-01-07 08:52:21

问题


Consider the following code:

public class Foo1
{
    public dynamic dowork()
    {
        return 10;
    }        
}

And in my Main , I call like:

int i = new Foo1().dowork();

The return value is 10. My question is why no Unboxing is required here?But in watch I've verified the Return Type of dowork is System.Object.


回答1:


It is unboxing - but it's doing it implicitly. There's an implicit conversion from any dynamic expression to any type. The exact conversion performed will depend on the execution-time type of the value.

From section 6.1.8 of the C# 5 specification:

An implicit dynamic conversion exists from an expression of type dynamic to any type T. The conversion is dynamically bound (§7.2.2), which means that an implicit conversion will be sought at run-time from the run-time type of the expression to T. If no conversion is found, a run-time exception is thrown.

(There's a slight nuance here in that it's a conversion from any expression of type dynamic rather than a conversion from the dynamic type itself. That avoids some conversion loops which would cause issues elsewhere in the spec.)



来源:https://stackoverflow.com/questions/31675973/unboxing-for-dynamic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!