使用隐式类型的局部变量 [英] Using implicitly typed local variables

查看:134
本文介绍了使用隐式类型的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚安装了 ReSharper 的试用版,并且第一件事注意到,它总是建议用隐式类型的局部变量替换显式类型局部变量,例如:

  public string SomeMethod(int aParam) 
{
int aNumber = SomeOtherMethod(aParam);
//应该更改为:
var aNumber = SomeOtherMethod(aParam);
}



我认为显式类型变量更易读>

你对ReSharper的建议有什么看法?使用隐式类型变量有什么优势吗?什么时候使用implicit / explict vars?

解决方案

我个人只使用var,当我可以清楚地区分变量Type只是读取声明,例如:

  var someVariable = new List< int>(); 

在上面的例子中,它显然var是指List< int> / p>

我不喜欢使用var,当我必须去一些方法定义,以找出什么变量类型var表示或通过不得不依赖于视觉工作室intelli-popup或任何调用,例如这不是对我确定:

  var someVaraible = SomeMethod 



我的意思是,SomeMethod函数应该返回什么?你可以看看代码行吗?不,你不能,所以这就是为什么我避免使用var这些情况。


I just installed a trial version of ReSharper and one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:

public string SomeMethod(int aParam)
{
    int aNumber = SomeOtherMethod(aParam);
    // should be changed to:
    var aNumber = SomeOtherMethod(aParam);
}

I think explicitly typed variables are more readable (more explicit).

What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?

解决方案

I personally only use "var" when I can clearly distinguish the variable Type by just reading the declaration, for example:

var someVariable = new List<int>();

In the example above, its evident that "var" refers to "List<int>".

I don’t like to use "var" when I have to go to some method definition to find out what variable type "var" represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:

var someVaraible = SomeMethod();

I mean, what is the "SomeMethod" function supposed to return? Can you tell just by looking at the line of code? No you can’t, so that is why I avoid using "var" on those situations.

这篇关于使用隐式类型的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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