什么是动态的(C#4)和VAR之间的区别? [英] What's the difference between dynamic(C# 4) and var?

查看:118
本文介绍了什么是动态的(C#4)和VAR之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一吨的有关新的关键字,将与C#V4出货的文章,但我不能让出一个动态和VAR之间的区别。

I had read a ton of articles about that new keyword that will ship with C# v4,but I couldn't make out the difference between a "dynamic" and "var".

<一个href=\"http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx\">This文章,让我想想吧,但我仍然看不出任何区别。

This article made me think about it,but I still can't see any difference.

难道你可以使用VAR只能作为局部变量,而是动态的本地和全球性的?

Is it that you can use "var" only as a local variable,but dynamic as both local and global?

我为我的无知抱歉,但你可以展示一些code,而不动态关键字,然后表现出同样的code动态关键字?

I'm sorry for my ignorance,but could you show some code without dynamic keyword and then show the same code with dynamic keyword?

推荐答案

VAR 是静态类型化 - 编译器和运行时的了解的类型 - 他们只是为您节省一些打字...以下是100%相同的:

var is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:

var s = "abc";
Console.WriteLine(s.Length);

string s = "abc";
Console.WriteLine(s.Length);

所有这一切发生的是,在编译想通了,取值必须是(从初始化)的字符串。在这两种情况下,它知道(在伊利诺斯州)的 s.Length 指(实例) string.length减属性

All that happened was that the compiler figured out that s must be a string (from the initializer). In both cases, it knows (in the IL) that s.Length means the (instance) string.Length property.

动态非常不同的野兽;它是最类似于对象,而是用动态调度:

dynamic is a very different beast; it is most similar to object, but with dynamic dispatch:

dynamic s = "abc";
Console.WriteLine(s.Length);

在这里,取值键入动态即可。它不知道关于 string.length减,因为它不知道的任何关于取值在编译时。例如,下面将汇编(但不运行)太:

Here, s is typed as dynamic. It doesn't know about string.Length, because it doesn't know anything about s at compile time. For example, the following would compile (but not run) too:

dynamic s = "abc";
Console.WriteLine(s.FlibbleBananaSnowball);

在运行时(只),它会的检查的为 FlibbleBananaSnowball 属性 - 无法找到它,并在一阵火花引起爆炸。

At runtime (only), it would check for the FlibbleBananaSnowball property - fail to find it, and explode in a shower of sparks.

使用动态,属性/方法/运营/等在运行时解析,根据实际的对象。非常方便的交谈COM(可以只运行的属性),DLR的,或其他动态系统,如的JavaScript

With dynamic, properties / methods / operators / etc are resolved at runtime, based on the actual object. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, like javascript.

这篇关于什么是动态的(C#4)和VAR之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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