C#中var和dynamic之间有什么区别? [英] What is the difference between var and dynamic in C#?

查看:204
本文介绍了C#中var和dynamic之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var在应用程序中声明了一些值,但是动态从未使用过。但是要求是使用。所以我必须使用any.suggest me我必须选择哪一个。



我尝试了什么:



var在应用程序中声明了一些值,但动态从未使用过。但是要求是use.so我必须使用any.suggest我必须选择哪一个。

var declared in application with some value assigned.but dynamic never used.but the requirement is to use.so I have to use anyone.suggest me which one i have to choose.

What I have tried:

var declared in application with some value assigned.but dynamic never used.but the requirement is to use.so I have to use anyone.suggest me which one i have to choose.

推荐答案

变量的类型,用<$ c $声明c> var ,在编译时被确认。例如,如果您编写 var i = 5; ,那么编译器会将其识别为 int 并进行编译例如,如果您在 i 中调用不存在的函数,则会出错。



<的类型 dynamic 变量,仅在运行时确认。如果你写 dynamic i = 5; ,编译器不关心它是什么类型。如果您使用 i 执行无效操作,例如,如果您调用 i.SomethingThatDoesNotExist(); ,则编译器赢了不给出错误。但是如果你运行应用程序,它就会崩溃。



什么时候应该使用 dynamic ?一个好的规则是:只使用动态,如果不使用它是痛苦的。这意味着,如果你可以避免它,你最好避免它。在这里查看更详细的解释: c# - 是使用动态被认为是一种不好的做法? - 堆栈溢出 [ ^ ]
The type of a variable, declared with var, is acknowledged at compile-time. For example if you write var i = 5;, then the compiler recognizes it as an int and will give a compilation error if you call, for example, a non-existing function in i.

The type of a dynamic variable, is only acknowledged at run-time. If you write dynamic i = 5;, the compiler doesn't care what type it is. If you do something invalid with i, for example if you call i.SomethingThatDoesNotExist();, then the compiler won't give an error. But if you run the application, it will crash on the line.

When should one use dynamic? A good rule to follow is: only use dynamic if not using it is painful. That means, if you can avoid it, you better do avoid it. Look here for a more detailed explanation on that: c# - Is the use of dynamic considered a bad practice? - Stack Overflow[^]


使用var声明的变量是隐式但静态类型的。使用dynamic声明的变量是动态类型的。 ...当使用'var'关键字时,类型由编译器在编译时决定,而当使用'dynamic'关键字时,类型由运行时决定
Variables declared with var are implicitly but statically typed. Variables declared with dynamic are dynamically typed. ... When using the 'var' keyword, the type is decided by the compiler at compile time, whereas when using the 'dynamic' keyword, the type is decided by the runtime


这篇关于C#中var和dynamic之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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