取消装箱动态类型 [英] Unboxing for dynamic type

查看:150
本文介绍了取消装箱动态类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

/ code>,我调用像:

And in my Main , I call like:

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

返回值为10.我的问题是为什么没有取消装箱 我已经验证了 的返回类型 > dowork System.Object

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.

推荐答案

是开箱 - 但它是隐式做。有一个从任何动态表达式到任何类型的隐式转换。

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.

从C#5规范的第6.1.8节开始:

From section 6.1.8 of the C# 5 specification:


隐式动态转换从动态的表达式存在到任何类型 T 。转换是动态绑定的(§7.2.2),这意味着将在运行时从表达式的运行时类型到 T 查找隐式转换。如果没有找到转换,则会抛出运行时异常。

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.

(这里有一点细微差别,类型动态表达式,而不是从动态类型转换,转换循环,这将导致spec中其他地方的问题。)

(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.)

这篇关于取消装箱动态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆