C# 3.0 中的 var 关键字

发布于 2024-07-27 04:13:55 字数 254 浏览 6 评论 0原文

可能的重复:
var 关键字有什么意义?

大家好,

我想确认我的理解是否正确。 如果我不使用 LINQ,那么使用 var 的唯一好处就是简洁? 这样的理解正确吗?

Possible Duplicate:
What’s the point of the var keyword?

Hello everyone,

I want to confirm whether my understanding is correct. If I do not use LINQ, then the only benefit of using var is to make brevity? Is that correct understanding?

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

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

发布评论

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

评论(9

儭儭莪哋寶赑 2024-08-03 04:13:56

如果您不使用 LINQ,var 只允许您声明变量的类型一次,而不是两次。

示例

var myObject = new MyObject();

vs

MyObject myObject = new MyObject();

这只能在本地完成,对于声明匿名类型也很有用。

例子

var myAnon = new { Name = "Something", Count = 45 };

If you're not using LINQ, var allows you to only declare the type of the variable once, instead of twice.

Example

var myObject = new MyObject();

vs

MyObject myObject = new MyObject();

This can only be done locally, and is also useful for declaring anonymous types.

Example

var myAnon = new { Name = "Something", Count = 45 };
碍人泪离人颜 2024-08-03 04:13:56

除了 LINQ 查询之外,我在使用 var 关键字时会非常谨慎。 在某些特定情况下,您只需要匿名类型,但我认为这种情况很少见。 Var 可能会导致非常混乱的代码,因为除非您使用智能感知拐杖,否则您在阅读代码时不知道正在处理的类型是什么。

让我越来越担心的是,我看到这么多的代码片段和代码位执行以下操作...它很懒,而不是 var 关键字的目的:

// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();

// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();

所以将它用于 LINQ...将它用于匿名类型(如果如果您确实在 LINQ 之外使用了匿名类型,那么您应该仔细检查为什么需要这样做)。

引用 MSDN (文章的最后一行)有关 var 使用的内容:

但是,使用 var 至少有可能使其他开发人员更难以理解您的代码。 因此,C# 文档通常仅在需要时才使用 var。

不要将其用作节省击键的捷径,下一个查看您代码的人会欣赏它。

Other than for LINQ queries I would be very cautious in using the var keyword. There are specific instance when you just need an anonymous type but this is few and far between I think. Var can lead to very confusing code as you have no idea what the type you are dealing with when reading the code unless you use the intellisense crutch.

It worries me more and more that I see so many snippets and bits of code that do the following... it's lazy and not what the var keyword was intended for:

// Not too bad but still shouldn't be done because the only gain you have is keystrokes
var Something = new SomeObject();

// Type here is not obvious, are you getting an int, double, custom object back???
var Something = GetLengthOfSpaghettiCode();

So use it for LINQ... use it for anonymous types (if you do use anonymous types outside of LINQ you should really scrutinize why you need to).

Quote from MSDN (very last line of article) regarding use of var:

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

Don't use it as a short cut to save keystrokes, the next guy looking at your code will appreciate it.

梦与时光遇 2024-08-03 04:13:56

差不多,是的。 var 可以用在编译器可以从您分配给变量的任何值推断变量类型的地方。 (但是,类型推断规则相当复杂,因此您可能需要阅读 C# 规范才能完全理解。)

这并不完全正确,因为需要 var 关键字用于定义匿名类型。 例如:

var foo = new { abc = 1, def = 2 };

当然,它可以在 LINQ 查询之外使用,也可以在内部使用。

Pretty much, yes. var may be used wherever the compiler can infer the type of the variable from whatever value you are assigning to it. (The type inference rules are quite complex however, so you may want to read the C# specification for a full understandin.)

It's not quite correct in that the var keyword is required for defining anonymous types. For example:

var foo = new { abc = 1, def = 2 };

which can be used outside of LINQ queries as well as inside, of course.

落叶缤纷 2024-08-03 04:13:56

我不认为使用 var 应该是一个问题 - 而且我更喜欢它正是因为代码可读性的原因。 首先,var 只是语法糖,并且在发出 IL 时被编译为正确的类型。 就代码可读性而言,关注变量的用途以及如何分配它而不仅仅是其类型更有意义。 VS .NET 编辑器无论如何都会在其后面的行中显示类型 - 如果您将鼠标悬停在其上。 所以这根本不应该是一个问题。 就调试而言 - 如果您看到“自动/本地/监视”窗口 - 它们会显示所有成员的类型。

对我来说,看到这样的代码更有意义:

var customers = GetCustomerList();
foreach (var customer in customers)
{
  customer.ProcessOrders();
}

与 var 相反,

List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
  customer.ProcessOrders();
}

它的公平性仅限于在局部变量声明中使用,而局部变量声明也在声明时初始化。 在这种情况下,如果省略实际类型,在我看来肯定会提高可读性。

编辑:对我来说,不警告以下用法是不公平的:

var x = 20;

这不好; 当文字适用于多种类型时,您需要知道文字的默认类型,从而了解 x 的类型推断出的内容。 是的,无论如何,我会避免这样的声明。

I don't think using var should be a problem - and I prefer it for exactly the reasons of code readability. First of all, var is only syntactic sugar and just gets compiled away to a proper type when IL is emitted. And as far as the code readability goes, it makes more sense to focus on the purpose the variable is used for, and how it is assigned than just its type. VS .NET editor shows the type in the line following it anyway - if you just hover on it. So this shouldn't be a problem at all. And as far as the debugging goes - if you see Autos/Local/Watch windows - they display the types of all the members.

It makes more sense for me to see code like this:

var customers = GetCustomerList();
foreach (var customer in customers)
{
  customer.ProcessOrders();
}

as opposed to

List<CustomerObjectDeserializedFromWebService> customers = GetCustomers();
foreach (CustomerObjectDeserializedFromWebService customer in customers)
{
  customer.ProcessOrders();
}

var is in its fairness limited to using in local variable declarations which are also initialized at the time of declaration. And in that one case, if you omit the actual type it definitely improves readability IMO.

EDIT: And it would unfair on my part not to warn against the usages as below:

var x = 20;

This is not good; when the literal is applicable to multiple types, you need to know the default type of the literal and hence understand what is infered for the type of x. Yes, by all means, I would avoid such declarations.

过气美图社 2024-08-03 04:13:56

我相信在处理通过 Web 服务等获取的数据时,它也被用在 WCF(Windows 通信基金会)中。

I believe it is also used in the WCF (Windows communication Foundation) when dealing with data obtained via webservices and the like.

§对你不离不弃 2024-08-03 04:13:56

我还发现使用 var 还可以简化低耦合设计中的重构。 这是因为我们倾向于强类型变量,但通常后面的代码需要较弱的类型。 使用 var 可以抵消编译器的类型更改。

I've also found that the use of var also eases refactoring in low-coupled designs. This is because we tend to strong type variables, but normally the code that follows is expecting weaker types. Using var you'll offset type changes to the compiler.

溇涏 2024-08-03 04:13:55

不,您可以使用 var 构造匿名类型< /a>,无论您是否使用 LINQ:

var anon = new { Name = "Anonymous", Age = 42 };

No, you can use var to construct anonymous types, regardless of whether or not you're using LINQ:

var anon = new { Name = "Anonymous", Age = 42 };
陌上青苔 2024-08-03 04:13:55

使用这样的类型也更容易。 当泛型类型很长时,类型名称可能会妨碍将变量名称直观地识别为声明的一部分。

Dictionary<string, Dictionary<int, ICollection<object>>>

特别是如果你返回并将其更改为

Dictionary<string, IDictionary<int, ICollection<object>>>

It's also easier for working with types like this. When you have very long generic types, the type name can get in the way of visually identifying the variable name as part of a declaration.

Dictionary<string, Dictionary<int, ICollection<object>>>

especially if you go back through and change it to

Dictionary<string, IDictionary<int, ICollection<object>>>
风尘浪孓 2024-08-03 04:13:55

来自msdn:

从 Visual C# 3.0 开始,变量
在方法范围内声明的可以
有一个隐式类型 var。 一个
隐式类型局部变量是
强类型就像你有
自己声明了类型,但是
编译器确定类型。 这
以下两个 i 声明是
功能等效:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

MSDN 链接

From msdn:

Beginning in Visual C# 3.0, variables
that are declared at method scope can
have an implicit type var. An
implicitly typed local variable is
strongly typed just as if you had
declared the type yourself, but the
compiler determines the type. The
following two declarations of i are
functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

MSDN Link Here

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