使用var或不使用var [英] Using var or not using var

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

问题描述

可能重复:
C#'var'与特定类型的性能

大家好,
我最近看到了很多使用 var 的代码.
例如:

Hi all,
I recently saw code that uses var a lot.
E.g.:

var myString = GetAnyString();
var myInstance = GetClass();

代替

string myString = GetAnyString();
MyClass myInstance = GetClass();

除了可读性强(我认为使用 var 不太可读),使用它是否有优点和/或缺点?性能如何

Besides the readability (I think that using var is not very readable), are there any advantages and/or drawbacks using it? How about performance

推荐答案

var由具有正确类型的编译器替换,因此,除了可能有很小的编译时间开销(veeeeeeeery很小)之外,不会对运行时性能造成影响.

var is replaced by the compiler with the right type, so there is no runtime performance hit, aside from a very small compile time overhead maybe (veeeeeeeery small).

实际上,从可读性的角度来看,我个人如下:

Actually, from a readability point of vue, I personally do as follows:

  • 变量实例化: object myVar = new object();

可变传播: var myVar = anotherVar.getComplexObject();

此外,当您具有非常复杂的类型实例化时,您可能会想使用它们,例如:

Also, you might be tempted to use them when you have a very complex type instantiation, like:

var myDict = new Dictionary<string, List<Tuple<string, object>>>();

在这里,它确实提高了可读性.

Here, it really improves readability.

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

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