var 隐式类型变量

版本新特性 / C# 3.0

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        // *** 以前 ***
        // 过去类型要写两遍,类型越长,这一行越难读
        Dictionary<string, List<int>> scoresOld = new Dictionary<string,
            List<int>>();
        scoresOld["Ann"] = new List<int>();
        scoresOld["Ann"].Add(5);
        foreach (KeyValuePair<string, List<int>> pair in scoresOld)
            Console.WriteLine(pair.Key + " " + pair.Value.Count);

        // *** 在 3.0 版本中 ***
        var scores = new Dictionary<string, List<int>>();   // 取自右侧
        scores["Ann"] = new List<int>();
        scores["Ann"].Add(5);
        foreach (var pair in scores)
            Console.WriteLine(pair.Key + " " + pair.Value.Count);

        var count = 0;                 // int
        var ratio = 1.5;               // double
        var name = "Bob";              // string
        Console.WriteLine(count + " " + ratio + " " + name);

        // var 不是“任意类型”:类型在声明时固定,之后永远不变
        // count = "seven";            // would not compile
        // var empty;                  // 无法编译:没有可供推断的依据
        // var nothing = null;         // 这一行同样不行
    }
}