动态(C#4)和var有什么区别? [英] What's the difference between dynamic (C# 4) and var?
问题描述
我已经阅读了很多有关C#v4附带的新关键字的文章,但我看不出动态和动态之间的区别。
I had read a ton of articles about that new keyword that is shipping with C# v4, but I couldn't make out the difference between a "dynamic" and "var".
这篇文章让我考虑了一下,但我仍然无法考虑看到任何区别。
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?
您可以显示一些没有动态关键字的代码,然后再显示具有动态关键字的相同代码吗?
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
必须是字符串(来自初始化程序)。在这两种情况下,它都知道(在IL中) 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.
动态
是非常不同的野兽;它与 object
最相似,但是具有动态分派:
dynamic
is a very different beast; it is most similar to object
, but with dynamic dispatch:
dynamic s = "abc";
Console.WriteLine(s.Length);
在这里,输入 s
保持动态。它不知道 string.Length
,因为它不知道关于 s $ c $的任何事情
c>在编译时。例如,以下代码也将编译(但不运行):
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.
具有 dynamic
,属性/方法/运算符/等根据实际对象在运行时解析。与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屋!