动态与对象相同 [英] Is dynamic is same as Object

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

问题描述

在通过C#进行CLR"一书中,提到了与FCL类型相对应的动态关键字是System.Object.请对此进行澄清.

In "CLR via C#" book it's mentioned that dynamic keyword corresponding FCL type is System.Object. please clarify this .

推荐答案

从C#的角度来看,这根本不是同一件事……但是在编译后的代码中,变量声明为类型 dynamic 通常(可能总是)与CLR字段或类型为 object 的局部变量相对应.

It's not the same thing from the C#'s point of view at all... but in the compiled code, a variable declared as type dynamic will usually (possibly always) correspond with a CLR field or local variable of type object.

C#编译器负责确保任何使用该值的源代码都具有动态行为. object 只是表示形式用于存储的编译器.它还应用了 [动态] 属性,以便其他代码知道该属性将被动态处理.

The C# compiler is responsible for making sure that any source code using that value has the dynamic behaviour applied to it. object is simply the compiler the representation uses for storage. It also applies the [Dynamic] attribute where appropriate, so that other code knows it's to be treated dynamically.

例如,考虑一下:

public class Foo
{
    public dynamic someField;
}

我相信它将被编译成等同于以下内容的IL:

I believe that will be compiled into IL equivalent to:

public class Foo
{
    [Dynamic]
    public object someField;
}

现在写:

Foo foo = new Foo();
foo.someField = "hello";
Console.WriteLine(foo.someField.Length);

编译器使用该属性来知道 foo.someField 是动态的,因此应该动态绑定 Length 属性.

the compiler uses the attribute to know that foo.someField is dynamic, so the Length property should be dynamically bound.

这篇关于动态与对象相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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