visual-studio 为什么要使用隐式类型的局部变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3582500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 12:23:07  来源:igfitidea点击:

Why should I use implicitly typed local variables?

c#visual-studioresharper

提问by Ash

When I say

当我说

public static IMyType GetGateWayManager()
{
    IUnityContainer _container = GetContainer();
    IMyType _gateWayManager = _container.Resolve<IMyType>();
    return _gateWayManager;
}

it comes with a warning saying Use implicitly types local variable.

它带有警告说Use implicitly types local variable

If I change it to

如果我把它改成

public static IMyType GetGateWayManager()
{
    IUnityContainer _container = GetContainer();
    var _gateWayManager = _container.Resolve<IMyType>();
    return _gateWayManager;
}

it is fine.

没事。

Can anyone can tell me why the VS editor thinks it is best practice to use var here?

谁能告诉我为什么 VS 编辑器认为在此处使用 var 是最佳实践?

采纳答案by Greg Beech

Who are types for?

类型适合哪些人?

The compiler? Yes, absolutely. The compiler uses types to make it more likely that your program will function correctly at runtime by ensuring the types match up, you're calling methods that actually exist, and passing them parameters of the right type. Here, the compiler is checking that you're actually returning something of type IMyType.

编译器?是的,一点没错。编译器使用类型通过确保类型匹配、调用实际存在的方法并向它们传递正确类型的参数来使您的程序更有可能在运行时正确运行。在这里,编译器正在检查您是否确实返回了 type 的内容IMyType

The editor? Again, yes. The editor uses background compilation and type information to help you write code. When you hit .after _containerit uses type information to tell you that there's a Resolvemethod and what parameters it takes.

编辑?再次,是的。编辑器使用后台编译和类型信息来帮助您编写代码。当你点击它时._container它使用类型信息告诉你有一个Resolve方法和它需要什么参数。

You? Not so much. We've already seen that the compiler will ensure that you return something of type IMyType, so why do you care about declaring it as that type when the compiler can work it out and check it for you? Similarly, the editor will tell you about the methods on the container, so why do you care about declaring whether it's a Unity container or some other type of container, given you already know from the variable name it's a container of some kind and from the editor that it has a Resolvemethod.

你?没那么多。我们已经看到编译器会确保您返回 type 的东西IMyType,那么当编译器可以解决并为您检查时,您为什么还要关心将其声明为该类型呢?同样,编辑器会告诉你容器上的方法,那么你为什么要关心声明它是一个 Unity 容器还是其他类型的容器,因为你已经从变量名中知道它是某种容器,并且从编辑器它有一个Resolve方法。

There's no problem with declaring types for locals, but what ReSharper is telling you is that the compiler can work it out, so it's redundant information, and that your code could be clearer with implicit types and good variable names. For example, is the purpose of this code any less clear than the original sample?

为局部变量声明类型没有问题,但 ReSharper 告诉您的是编译器可以解决它,因此它是冗余信息,并且您的代码可以使用隐式类型和良好的变量名更清晰。例如,这段代码的目的是否比原始示例更不明确?

public static IMyType GetGateWayManager()
{
    var container = GetContainer();
    var gateWayManager = container.Resolve<IMyType>();
    return gateWayManager;
}

回答by Rúben Lício Reis

Using var instead of explicit type is suggested by resharper because it is clear and useful.

resharper 建议使用 var 而不是显式类型,因为它清晰且有用。

Clear because you has less code written and your focus is on variable name instead of type name. You might think type name is useful, but after a short time you will just forget it.

清楚,因为您编写的代码较少,并且您的重点是变量名称而不是类型名称。您可能认为类型名称很有用,但过一会儿您就会忘记它。

Useful because when you change a method type return you won't need to change all types in the way.

很有用,因为当您更改方法类型返回时,您不需要更改所有类型。

Example:

例子:

int id = getId();
List<MyType> myList = FindById(id);

In this situation if you change id from int to guid you must change this "int" here. This is small, but easily can become big in real life projects. With var you have exacly the some code for compiler and do not need to change it always.

在这种情况下,如果您将 id 从 int 更改为 guid,则必须在此处更改此“int”。这很小,但在现实生活项目中很容易变大。使用 var 您可以精确地获得编译器的一些代码,并且不需要总是更改它。

var id = getId();
var myList = FindById(id);

I used to prefer explicit types, but just few hours after try out var I won't let it so easily.

我曾经更喜欢显式类型,但在尝试 var 几个小时后,我不会那么容易地让它。

Remember: var is changed in compile time to correct type. It is different from dynamics which is not recomented in almost all cases.

请记住:var 在编译时更改为正确的类型。它不同于几乎在所有情况下都不推荐的动力学。

回答by Eugene Cheverda

May be it's ReSharper.

可能是 ReSharper。

ReSharper recommends using varwhen the type of variable can be seen in code. In your example we can see that _gateWayManagerwill be of type IMyType, then we use varkeyword for implicit typing of variable. _containerwill be explicitly typed in code because we can't say object of what type will be returned by GetContainer()

ReSharper 建议var在代码中可以看到变量类型时使用。在您的示例中,我们可以看到_gateWayManager它将是 type IMyType,然后我们使用var关键字来隐式键入变量。_container将在代码中显式键入,因为我们不能说将返回什么类型的对象GetContainer()

回答by CodingInsomnia

It's probably not the VS Editor, but rather ReSharper that is giving you that message. It's more a matter of taste than of best practice. But once you get used to the var keyword, you start to like it more and more. At least I've learned to love it.

可能不是 VS 编辑器,而是 ReSharper 向您提供了该信息。与其说是最佳实践,不如说是品味问题。但是一旦你习惯了 var 关键字,你就会越来越喜欢它。至少我学会了喜欢它。

回答by Giorgi

It's Resharper warning you, not VS editor.

这是 Resharper 警告您,而不是 VS 编辑器。

回答by Karl Giesing

The approved answer is certainly correct and answers the question as described.

批准的答案肯定是正确的,并按照描述回答问题。

But - I did want to bring up a case where you have touse implicit typing: when the variable represents an anonymous type.

但是 - 我确实想提出一个必须使用隐式类型的情况:当变量表示匿名类型时。

Consider this code:

考虑这个代码:

var upperLowerWords =
    from w in words
    select new { Upper = w.ToUpper(), Lower = w.ToLower() };

What type is upperLowerWordssupposed to be? You can't say, because there is no explicittype that matches what is returned - but it is a type that the compiler can recognize. And, in fact, it does.

upperLowerWords应该是什么类型?您不能说,因为没有与返回的内容匹配的显式类型 - 但它是编译器可以识别的类型。而且,事实上,确实如此。

For reference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables(which is where I got that example)

供参考:https: //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables(这是我得到那个例子的地方)