与 C# 中的显式类型相比,使用 var 有什么优势?

发布于 2024-09-13 09:12:08 字数 485 浏览 3 评论 0 原文

可能的重复:
var 关键字有什么意义?
C# 中 var 关键字的使用

我了解 IEnumerable<.. .> 对于数据类型可能会使代码的可读性稍差,或者嵌套泛型看起来有点令人畏惧。但除了代码可读性之外,使用 var 代替显式类型还有什么优点吗?似乎通过使用显式类型,您最好传达变量的功能,因为您知道它是什么。

如果它是工作场所编码标准,我会为了团队合作而使用它。然而,在我自己的项目中,我更喜欢避免使用 var。

Possible Duplicates:
What’s the point of the var keyword?
Use of var keyword in C#

I understand how IEnumerable<...> for a datatype can make the code a little less readable or how nested generics can seem a little daunting. But aside from code readability, are there advantages to using var instead of the explicit type? It seems like by using the explicit type, you'd better convey what the variable is capable of because you know what it is.

If it's a workplace coding standard, I use it for the sake of teamwork. In my own projects however, I prefer to avoid the user of var.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

柠檬色的秋千 2024-09-20 09:12:08

var 的目的是允许匿名类型,没有它,它们就不可能实现,这就是它存在的原因。我认为所有其他用途都是惰性编码。

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.

如梦初醒的夏天 2024-09-20 09:12:08

使用 var 作为 foreach 块的迭代器变量比显式类型名称更安全。例如,

class Item {
  public string Name; 
}
foreach ( Item x in col ) {
  Console.WriteLine(x.Name);
}

此代码可以在没有警告的情况下进行编译,但仍然会导致运行时转换错误。这是因为 foreach 循环适用于 IEnumerableIEnumerable。前者返回类型为 object 的值,而 C# 编译器只是在幕后为您转换为 Item。因此它是不安全的,并且可能导致运行时错误,因为 IEnumerable 可以包含任何类型的对象。

另一方面,以下代码将仅执行以下操作之一

  1. 不编译,因为 x 被输入为 object 或其他没有名称字段/属性的类型
  2. 编译并确保枚举时不会出现运行时转换错误。

IEnumerable 的情况下,“x”的类型将为 object;在 IEnumerable 的情况下,“x”的类型将为 T代码>.编译器不进行转换。

foreach ( var x in col ) {
  Console.WriteLine(x.Name);
}

Using var as the iterator variable for a foreach block is more type safe than explicit type names. For example

class Item {
  public string Name; 
}
foreach ( Item x in col ) {
  Console.WriteLine(x.Name);
}

This code could compile without warnings and still cause a runtime casting error. This is because the foreach loop works with both IEnumerable and IEnumerable<T>. The former returns values typed as object and the C# compiler just does the casting to Item under the hood for you. Hence it's unsafe and can lead to runtime errors because an IEnumerable can contain objects of any type.

On the other hand the following code will only do one of the following

  1. Not compile because x is typed to object or another type which does not have a Name field / property
  2. Compile and be guaranteed to not have a runtime cast error while enumerating.

The type of 'x' will be object in the case of IEnumerable and T in the case of IEnumerable<T>. No casting is done by the compiler.

foreach ( var x in col ) {
  Console.WriteLine(x.Name);
}
§对你不离不弃 2024-09-20 09:12:08

我喜欢它,尤其是在单元测试中,因为随着代码的发展,我只需要修复声明/赋值的右侧。显然,我还必须更新以反映使用情况的变化,但在声明时我只需要进行一项更改。

I like it, especially in unit tests, because as the code evolves I only have to fix up the right-hand side of the declaration/assignment. Obviously I also have to update to reflect the changes in usage, but at the point of declaration I only have to make one change.

寄离 2024-09-20 09:12:08

它不会对排放的 IL 产生有意义的变化。这只是一种代码风格偏好。

就我而言,我喜欢它,尤其是在处理具有长、通用、几乎不可读名称的类型时,例如 Dictionary>[]

It produces no meaningful change in the emitted IL. It is merely a code style preference.

I, for one, like it, especially when dealing with types that have long, generic, almost unreadable names such as Dictionary<string, IQueryable<TValue1, TValue2>>[].

末骤雨初歇 2024-09-20 09:12:08

var 只是一个语法糖。在编译时始终知道变量的类型。使用 var 关键字没有其他优点。

The var is just a syntactic sugar. It is always known at compile time what type the variable is. There are no other advantages of using the var keyword.

相思故 2024-09-20 09:12:08

没有任何真正的差异。有些人建议使用显式类型,因为它可以使代码维护更容易。然而,推动 var 的人们的立场是“如果我们使用 var,我们就被迫使用良好的命名约定”。

当然,如果您使用变量的目的是拥有良好的命名约定,但这种约定失败了,那么接下来的事情会更加痛苦。 (国际海事组织)

There aren't any real differences. Some people suggest using the explicit type because it can make maintaining the code easier. However, people that push for var have the stance that "if we use var, we are forced to use good naming conventions".

Of course if you use vars with the intention of having good naming conventions and that breaks down, it's more painful down the road. (IMO)

满天都是小星星 2024-09-20 09:12:08
public IAwesome { string Whatever { get; } }
public SoCool : IAwesome { public string Whatever { get; } }

public HeyHey
{
    public SoCool GetSoCool() { return new SoCool(); }

    public void Processy()
    {
        var blech = GetSoCool();
        IAwesome ohYeah = GetSoCool();
        // Now blech != ohYeah, so var is blech and ohYeah is IAwesome.
    }
}
public IAwesome { string Whatever { get; } }
public SoCool : IAwesome { public string Whatever { get; } }

public HeyHey
{
    public SoCool GetSoCool() { return new SoCool(); }

    public void Processy()
    {
        var blech = GetSoCool();
        IAwesome ohYeah = GetSoCool();
        // Now blech != ohYeah, so var is blech and ohYeah is IAwesome.
    }
}
旧夏天 2024-09-20 09:12:08

除了您提到的可读性方面之外,“var”还具有降低微不足道的代码更改破坏代码其他部分的可能性的好处。例如,如果您重命名类型。或者,如果您切换到与以前的类型大部分兼容的不同类型(例如从 Foo[] 更改为 IEnumerable),那么您只需要做更少的工作即可将代码恢复到可编译状态。

Besides the readability aspect you mentioned, 'var' also has the benefit of reducing the probability that a trivial code change will break other parts of your code. If you rename a type, for example. Or if you switch to a different type that is mostly compatible with the former type (e.g. changing from Foo[] to IEnumerable) you have much less work to do to get your code back to a compilable state.

未蓝澄海的烟 2024-09-20 09:12:08

您可以抽象出技术细节的心理复杂性,只专注于模型中的问题领域。你必须确保你的变量被有意义地命名。

You can abstract away the mental complexity of the technicalities to focus purely on the problem domain from your model. you have to make sure your variables are named meaningfully tho.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文