在C#3.0 var关键字的优势 [英] Advantage of var keyword in C# 3.0

查看:124
本文介绍了在C#3.0 var关键字的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

复制:

使用VAR或对象名称类型什么

我做不到理解var关键字在C#3.0中需要的是在使用它的优势。
I看到这个的问题,但不明白使用的真正目的它

I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it. i saw this question but did not understand the real purpose of using it

推荐答案

这主要是目前对LINQ,当你可以使用一个匿名类型的投影:

It's mostly present for LINQ, when you may use an anonymous type as the projection:

var query = from person in employees
            where person.Salary > 10000m
            select new { FullName=person.Name, person.Department };

下面查询的类型不能显式声明的,因为匿名类型没有名字。 (在现实世界情况下,匿名类型通常包含来自多个对象的值,所以没有命名的类,其中一个包含所有属性。)

Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.)

这是实际上,当你使用一个潜在的长期类型名称初始化的变量(通常是由于仿制药),只是调用构造函数非常有用 - 它增加了信息的密度(降低冗余)。有相同的信息量这两行:

It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines:

List<Func<string, int>> functions = new List<Func<string, int>>();
var functions = new List<Function<string, int>>();



,但第二个表达它以更紧凑的方式

but the second one expresses it in a more compact way.

当然,这的可以的被滥用,如:

Of course this can be abused, e.g.

var nonObviousType = 999999999;



但很明显类型的变量是什么,我相信它可以显著增加可读性。

but when it's obvious what the type's variable is, I believe it can significantly increase readability.

这篇关于在C#3.0 var关键字的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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