在开发中到底要不要用var?
var是.net的一个语法糖,在Resharper中推荐都使用这个关键字,平常我也是经常用;但是在跟其他程序员推广使用时,他的一些考虑引发了我的深思,到底该不该使用这个关键字呢?
我使用的理由
我使用的理由很简单
简化输入。这个真的很方便,你想想你new一个对象的时候,或者通过一个方法的时候,还得想想这个对象的类型是什么,尤其是像这种复杂的类型:
Func<Dictionary<Model.User,List<Model.Roles>>,int> test=new Func<Dictionary<Model.User,List<Model.Roles>>,int>(),用起来得有多辛苦?Resharper强制的时候,你看着Resharper的推荐,总是忍不住的点一下,结果整个VS都是var的类型了
强迫症。如果用各种类型,在new的时候左边总是对不齐,但是用var就不同了
var obj1=new List<Model.User>();
var obj2=new Dictionary<int,Model.Department>();
左边对的多齐是不?
不使用的理由
同事给我的理由是:用这个关键字,你就没法知道一个这个对象的类型了,尤其在记事本打开的时候,很不爽。只有用vs打开的时候,通过智能感知才知道。
这确实是个问题,我一时也不能反驳。但是隐隐约约我又感觉有点不对。我用这么久了,也没什么问题是不,也没有感觉到使用不方便啊。话说了,开发C#的,有几个又不打开VS的?
让我们看看老外是怎么看的
在文章To var or not to var – c# implicit variable declaration中提到:
What are the benefits of using var
- Dont Repeat Yourself (DRY) – Redundant code should be avoided.
- Faster creation of code
- Calls for improved naming of variables – can work as a reminder for descriptive naming
- Improved readability – in some cases (where the repeated type is long and complex)
- Less code modification if you later need to change the type
- Clearer distinction of when you really want to specify the type
The disadvantages of using var
- Loss of readability – in some cases (where the type isn’t obvious)
- Changes to the type could introduce bugs which the compiler otherwise would have caught for the developer
Conclusion:
In my opinion the var keyword should certainly be used with care, but redundant declarations should be avoided. Therefore it would be preferred to use implicit declarations wherever it’s appropriate, i.e where the type is clear and obvious. Consistency shouldn’t be neglected, but I believe most developers in an organisation would identify the same situations where the type is ambigous.
In the end it’s really about finding a sensible balance. If keeping in mind to use var to avoid repetition and obvious type declarations, the answer is pretty clear of when to var or not… where the type is reasonably obvious.
在文章“WHAT ADVANTAGES DOES USING VAR HAVE OVER THE EXPLICIT TYPE IN C#? [DUPLICATE]”有人是这么认为的:
The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.
你是想懒点,还是想累点?
这篇文章总结得也不错“C# 3.0 Implicit Type Declarations: To var or not to var?”
Some cases where it seems just fine to suggest var are:
- New object creation expression: var dictionary = new Dictionary<int, string>();
- Cast expression: var element = (IElement)obj;
- Safe Cast expression: var element = obj as IElement;
- Generic method call with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService()
- Generic static method call or property with explicit type arguments, when return type is generic: var manager = Singleton.Instance;
Infoq中有篇文章研究得比较深入:“C# Debate: When Should You Use var?”
Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.
但是,有人提出了另外的意见:
Chris Sutton seems to go further and implies that the type really doesn't matter.Then the suggestion came up that you should only use var when you don’t know the type. Here is where I differ in opinion and usage. Look at the following snippet
var procs = from p in ServiceController.GetServices()
where p.Status == ServiceControllerStatus.Running
select p;
procs.ToList().ForEach(p=> Console.WriteLine(p.ServiceName));
procs is certainly IEnumerable but it doesn’t matter to me. I primarily care that procs is a list and that the individual items in the list have a Property called ServiceName. The underlying type is important to the compiler, but the people that have to read code aren’t compilers right?
总结
使用var可以:
- 减少编程语言中的重复工作(DRY)
- 减少编程中的噪声干扰
- 减少编码
- 在某些情况下,会提升可阅读性
因此在以下情况,建议使用var
- 当你能够通过一个声明明确的看到类型时。如:
var dic=new Dictionary<int,List<string>>();、var element = (IElement)obj、var element = obj as IElement - 使用泛型时:
var manager = serviceProvider.GetService<IManager>()、var manager = Singleton<Manager>.Instance - 当你使用匿名类时:
var person = new { Name = "Peter", Age=4};
其他情况下建议还是书写完全的类型名称,因为过度使用var,会减低整体代码的可读性,尤其在没有IDE的智能提示的情况下,用var可能会导致阅读代码的人的困惑。
如何在Resharper中关闭这个提示

在开发中到底要不要用var?的更多相关文章
- MyBatis 项目开发中是基于 XML 还是注解?
只要你对 MyBatis 有所认识和了解,想必知道 MyBatis 有两种 SQL 语句映射模式,一种是基于注解,一种是基于XML. 基于 XML <mapper namespace=" ...
- 【Android进阶】在开发中Application到底用来做什么
首先,在一个Android程序中,有且只有一个Application对象,在程序开始跑起来的时候,首先执行Application的onCreate方法,这是一个Android应用的入口,在开发中,我们 ...
- 开发中,GA、Beta、GA、Trial到底是什么含义
前言 用过maven的都应该知道,创建maven项目时,其版本号默认会以SNAPSHOT结尾,如下: 通过英文很容易就可以知道这是一个快照版本.但是,在开发中,或者使用别的软件的时候,我们常常会见到各 ...
- 一个简单的特效引发的大战之移动开发中我为什么放弃jquery mobile
我本想安静的做一个美男子,可是,老板不涨工资,反而,一月不如一月. 我为什么放弃jquery mobile插件选择自己写特效? 在开发中大家都知道效率很重要,一个好的工具可以在开发中大大提升效率,工作 ...
- 彻底理解和解决移动WEB开发中CLICK点透问题
在移动WEB开发中,有时候可能会出现点透问题,本文将围绕这个TAP点透问题,详细的讲述到底什么是点透,为什么会出现点透,如何避免出现点透,如果不可避免的出现了,如何解决解决移动WEB开发中CLICK点 ...
- web开发中移动端适配
这个话题有些复杂,说起来有些琐碎,因为和移动端适配相关的问题太多了. 1. 概念 1.1 设备像素 设备像素被称为物理像素,它是显示设备中一个最小的物理部件.每个像素可以根据操作系统设置自己的颜色和亮 ...
- React在开发中的常用结构以及功能详解
一.React什么算法,什么虚拟DOM,什么核心内容网上一大堆,请自行google. 但是能把算法说清楚,虚拟DOM说清楚的聊聊无几.对开发又没卵用,还不如来点干货看看咋用. 二.结构如下: impo ...
- Android学习探索之Java 8 在Android 开发中的应用
前言: Java 8推出已经将近2年多了,引入很多革命性变化,加入了函数式编程的特征,使基于行为的编程成为可能,同时减化了各种设计模式的实现方式,是Java有史以来最重要的更新.但是Android上, ...
- Java开发中的23种设计模式详解
[放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...
随机推荐
- NodeJs之调试
关于调试 当我们只专注于前端的时候,我们习惯性F12,这会给我们带来安全与舒心的感觉. 但是当我们使用NodeJs来开发后台的时候,我想噩梦来了. 但是也别泰国担心,NodeJs的调试是很不方便!这是 ...
- ArcGIS 10.0紧凑型切片读写方法
首先介绍一下ArcGIS10.0的缓存机制: 切片方案 切片方案包括缓存的比例级别.切片尺寸和切片原点.这些属性定义缓存边界的存在位置,在某些客户端中叠加缓存时匹配这些属性十分重要.图像格式和抗锯齿等 ...
- pt-table-checksum
pt-table-checksum是percona公司提供的一个用于在线比对主从数据一致性的工具. 实现原理 将一张大表分成多个chunk,每次针对一个chunk进行校验,同时将校验的结果通过REPL ...
- JavaScript权威指南 - 对象
JavaScript对象可以看作是属性的无序集合,每个属性就是一个键值对,可增可删. JavaScript中的所有事物都是对象:字符串.数字.数组.日期,等等. JavaScript对象除了可以保持自 ...
- Java中用得比较顺手的事件监听
第一次听说监听是三年前,做一个webGIS的项目,当时对Listener的印象就是个"监视器",监视着界面的一举一动,一有动静就触发对应的响应. 一.概述 通过对界面的某一或某些操 ...
- python10作业思路及源码:类Fabric主机管理程序开发(仅供参考)
类Fabric主机管理程序开发 一,作业要求 1, 运行程序列出主机组或者主机列表(已完成) 2,选择指定主机或主机组(已完成) 3,选择主机或主机组传送文件(上传/下载)(已完成) 4,充分使用多线 ...
- ABP创建数据库操作步骤
1 ABP创建数据库操作步骤 1.1 SimpleTaskSystem.Web项目中的Web.config文件修改数据库配置. <add name="Default" pro ...
- JAVA装饰者模式(从现实生活角度理解代码原理)
装饰者模式可以动态地给一个对象添加一些额外的职责.就增加功能来说,Decorator模式相比生成子类更为灵活. 该模式的适用环境为: (1)在不影响其他对象的情况下,以动态.透明的方式给单个对象添加职 ...
- 编译器开发系列--Ocelot语言3.类型名称的消解
"类型名称的消解"即类型的消解.类型名称由TypeRef 对象表示,类型由Type 对象表示.类型名称的消解就是将TypeRef 对象转换为Type 对象. TypeResolve ...
- SymmetricDS 快速和灵活的数据库复制
开始谈谈开源的SymmetricDS,谈谈实际使用中,遇到的一些问题和解决办法.持续更新: SymmetricDS 快速和灵活的数据库复制 实际使用 和 埋过的坑 (一)知识篇 SymmetricDS ...