C#中的Dynamic vs var [英] dynamic vs var in C#

查看:84
本文介绍了C#中的Dynamic vs var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

dynamic(C#4)和var有什么区别?

.NET 4.0(VS 2010)中的dynamic和var关键字之间有什么区别。根据MSDN,动态的定义是-动态查找使您可以编写方法,运算符和索引器调用,属性和字段访问,甚至对象调用,而这些对象调用会绕过C#的常规静态绑定,而是动态地进行解析

What is the difference between dynamic and var keyword in .NET 4.0 (VS 2010). As per MSDN, the definition of dynamic is - Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the normal static binding of C# and instead gets resolved dynamically.

而var的定义是-强类型化隐式类型的局部变量,就像您自己声明了该类型一样,但是编译器确定类型

下面的代码上下文有何不同:

How is this different in the code context below:

var a1 = new A();
a1.Foo(1);

dynamic a2 = new A();
a2.Foo(1);


推荐答案

var 表示推断出 static 类型-在您的情况下,它完全等效于

var means the static type is inferred - in your case it's exactly equivalent to

A a1 = new A();

所有绑定仍然完全静态地完成。如果您查看生成的代码,它将与上面的声明完全相同。

All the binding is still done entirely statically. If you look at the generated code, it will be exactly the same as with the above declaration.

dynamic 表示所有使用 a2 的表达式都在执行时而不是在编译时绑定,因此它可以动态运行。编译器不会检查 Foo 方法是否存在-行为是在执行时确定的。确实,如果对象实现 IDynamicMetaObjectProvider ,则它可以在执行时决定对调用进行处理,以响应 any 方法调用(或其他类型的调用)。使用)-换句话说,根本没有所谓的 Foo 的真实方法。

dynamic means that all any expression using a2 is bound at execution time rather than at compile-time, so it can behave dynamically. The compiler won't check whether the Foo method exists - the behaviour is determined at execution time. Indeed, if the object implements IDynamicMetaObjectProvider it could decide what to do with the call at execution time, responding to any method call (or other kind of use) - in other words, there doesn't have to be a "real" method called Foo at all.

如果您在动态情况下查看生成的代码,则会发现与呼叫站点和绑定程序有关的各种奇怪而奇妙的东西。

If you look at the generated code in the dynamic situation, you'll find all kinds of weird and wonderful stuff going on to do with call sites and binders.

这篇关于C#中的Dynamic vs var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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