跳转到内容

C# 编程/关键字/var

来自 Wikibooks,开放的书籍,开放的世界

在声明变量时,可以用 var 关键字代替类型,从而让编译器推断变量的类型。此功能可用于缩短变量声明,尤其是在实例化泛型类型时,甚至在使用 LINQ 表达式时也是必要的(因为查询可能会生成非常复杂的类型)。

以下

int num = 123;
string str = "asdf";
Dictionary<int, string> dict = new Dictionary<int, string>();

等同于

var num = 123;
var str = "asdf";
var dict = new Dictionary<int, string>();

var 不会 创建“变体”类型;类型只是由编译器推断出来的。在无法推断类型的情况下,编译器会生成错误。

var str; // no assignment, can't infer type

void Function(var arg1, var arg2) // can't infer type
{
    ...
}



C# 关键字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
特殊的 C# 标识符(上下文关键字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文关键字(用于查询)
ascending by descending equals from
group in into join let
on orderby select where

注意:Var 不是关键字

华夏公益教科书