跳轉到內容

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 不是關鍵字

華夏公益教科書