使用隐式类型的局部变量

编程入门 行业动态 更新时间:2024-10-26 02:28:28
本文介绍了使用隐式类型的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我刚刚安装了 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.

更多推荐

使用隐式类型的局部变量

本文发布于:2023-11-10 22:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   局部   类型   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!