请问新的“动态”C#4.0关键字弃用“无功”的关键字? [英] Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?

查看:186
本文介绍了请问新的“动态”C#4.0关键字弃用“无功”的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#4.0出来,我们有动态关键字作为由Anders Hejlsberg为在这个优秀的演讲中描述,( C#是不断发展的速度比我能跟得上..我没有太多的时间来熟悉自己使用var关键字)



我还需要var关键字?有没有什么VAR可以做..动态不能



  VAR X = SomeFunctionThatIKnowReturnsSomeKindOfList()?; 
//做X

动感的东西X = SomeFunctionThatIKnowReturnsSomeKindOfList();
//做随x


解决方案

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



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

这篇关于请问新的“动态”C#4.0关键字弃用“无功”的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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