且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

请问新的“动态”C#4.0关键字弃用“无功”的关键字?

更新时间:2022-10-23 19:44:37

没有的东西,他们是非常不同的。



VAR 表示在编译时推断变量的类型。 - 但它仍然是完全静态绑定



动态表示假设我可以做任何事情,我想和这个变量。 - 即编译器不知道哪些操作是可用的,而DLR将制定出什么样的呼吁的真正的意思是在执行时间。



我指望用动态很少 - 只有当我真正想要的动态行为:




  • VAR 让你赶上在编译时错别字等

  • 静态绑定代码总是会跑的比动态绑定的代码快(即使差别变得相当小)

  • 静态绑定代码提供了更多的编译时支持不仅仅是错误:你能找到调用层次结构,重构会更好地工作,智能感知可等


When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)

Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?

var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x

No, they're very different.

var means "infer the type of the variable at compile-time" - but it's still entirely statically bound.

dynamic means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls really mean at execution time.

I expect to use dynamic very rarely - only when I truly want dynamic behaviour:

  • var lets you catch typos etc at compile-time
  • statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
  • statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc