动态无功VS动态、VS

2023-09-08 09:03:21 作者:刀锋战神

可能重复:   What’s动态之间的差(C#4)和变种?中

什么是.NET 4.0(VS 2010)的动态和var关键字的区别。根据MSDN的,动态的定义是 - 动态查找,您可以编写方法,运算符和索引器调用,属性和字段访问甚至对象调用时,绕过正常的静态C#的结合,而是被动态地。

而对于VAR的定义是 - 的的隐式类型的局部变量是强类型的,就好像你有自己声明的类型,但是编译器确定类型的

这是如何的不同在下面的code方面:

  VAR A1 =新的A();
a1.Foo(1);

动态A2 =新的A();
a2.Foo(1);
 

解决方案

VAR 指的静态的类型推断 - 在你的情况正是相当于

  A A1 =新的A();
 

所有绑定仍然完成的完全的静态。如果你查看​​生成的code,这将是完全一样的上述声明。

动态意味着所有的任何EX pression使用 A2 必然会在执行时,而不是在编译 - 时间,这样可以动态的行为。编译器不会检查是否方法存在 - 的行为是在执行时确定的。事实上,如果对象实现 IDynamicMetaObjectProvider 就可以决定如何处理该呼叫在执行时,响应的任意的方法调用(或其他类型的使用) - 换句话说,有没有成为一个真正的方法称为所有

电网的谐波抑制与无功补偿的动态无功补偿装置系统 谐波抑制与无功补偿的关系解析及谐波抑制对无功补偿效果的分析

如果你看一下生成的code在动态情况下,你会发现各种怪异和奇妙的东西,事情做调用的地方和粘合剂。

Possible Duplicate: What’s the difference between dynamic(C# 4) and var?

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.

Whereas the definition for var is - An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

How is this different in the code context below:

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

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

解决方案

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