var关键字的作用是什么 [英] what is the function of var keyword

查看:125
本文介绍了var关键字的作用是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var关键字的功能是什么

what is the function of var keyword

推荐答案

Uma试图解释的称为类型推断,在C#v.3中引入.参见:
http://en.wikipedia.org/wiki/Type_inference [ http://msdn.microsoft.com/en-us/library/ms364047%28v = vs.80%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/库/ms364047%28v=vs.80%29.aspx#cs3spec_topic2 [ http://geekswithblogs.net/sdorman/archive/2007/04/06/111034.aspx [ ^ ].

注意从构造函数推断的类型,这是最重要的情况:

What Uma tried to explain is called type inference, introduced in C# v.3. See:
http://en.wikipedia.org/wiki/Type_inference[^],
http://msdn.microsoft.com/en-us/library/ms364047%28v=vs.80%29.aspx[^],
http://msdn.microsoft.com/en-us/library/ms364047%28v=vs.80%29.aspx#cs3spec_topic2[^].

I found pretty nice short explanation here: http://geekswithblogs.net/sdorman/archive/2007/04/06/111034.aspx[^].

Pay attention of type inferred from a constructor, this is a most important case:

var myInstance = new MyClass.Create(/*...*/);

//strictly equivalent to 
MyClass. myInstance = new MyClass.Create(/*...*/);
// (only without a need to write MyClass twice...)



可以从foreach的容器中推断出类型,从委托的类型中推断出参数的类型:



Type can be inferred from container in foreach, type of parameters inferred from the type of delegate:

myTextBox.KeyPress = (sender, eventArgs) => {
    // eventArgs can be used as KeyPressEventArgs,
    // inferred form the declaration of the event TextBox.KeyPress
}



这是推理的另一个重要案例,实际上是最重要的一个案例.

—SA



This is another important case of inference, practically the most important one.

—SA


var用于隐式类型的局部变量,该变量是强类型的,就像声明了类型一样自己,但由编译器确定类型.

有关更多信息,请参考以下内容:

http://msdn.microsoft.com/en-us/library/bb383973.aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/bb384061.aspx [ ^ ]

var基本上用在 LINQ 中,在那里我们不知道查询结果返回什么类型.

希望对您有所帮助:)
var is used for implicitly typed local variable, which is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

For more info refer these:

http://msdn.microsoft.com/en-us/library/bb383973.aspx[^]

http://msdn.microsoft.com/en-us/library/bb384061.aspx[^]

var is basically used in LINQ where we don''t know what type is returned from the query result.

hope it helps :)


var关键字可以表示可以在编译时确定的任何类型.
例如
The var keyword can represent any type that can be determined at compile-time.
For Example
public int ReturnValue()
{
    var a = 5;
    int b = 5;

    return a + b;
}


这篇关于var关键字的作用是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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