C#3.0新增功能06 對象和集合初始值設定項

使用 C# 能夠在單條語句中實例化對象或集合並執行成員分配。html

對象初始值設定項
使用對象初始值設定項,你能夠在建立對象時向對象的任何可訪問字段或屬性分配值,而無需調用後跟賦值語句行的構造函數。 利用對象初始值設定項語法,你可爲構造函數指定參數或忽略參數(以及括號語法)。 如下示例演示如何使用具備命名類型 Cat 的對象初始值設定項以及如何調用無參數構造函數。 請注意,自動實現的屬性在 Cat 類中的用法。
public class Cat
{
    public int Age { get; set; }
    public string Name { get; set; }

    public Cat()
    {
    }

    public Cat(string name)
    {
        this.Name = name;
    }
}
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
Cat sameCat = new Cat("Fluffy"){ Age = 10 };

對象初始值設定項語法容許你建立一個實例,而後將具備其分配屬性的新建對象指定給賦值中的變量。git

從 C# 6 開始,除了分配字段和屬性外,對象初始值設定項還能夠設置索引器。 請思考這個基本的 Matrix 類:api

public class Matrix
{
    private double[,] storage = new double[3, 3];

    public double this[int row, int column]
    {
        // 嵌入的數組將酌情拋出超出範圍的異常。
        get { return storage[row, column]; }
        set { storage[row, column] = value; }
    }
}

可使用如下代碼初始化標識矩陣:數組

var identity = new Matrix
{
    [0, 0] = 1.0,
    [0, 1] = 0.0,
    [0, 2] = 0.0,

    [1, 0] = 0.0,
    [1, 1] = 1.0,
    [1, 2] = 0.0,

    [2, 0] = 0.0,
    [2, 1] = 0.0,
    [2, 2] = 1.0,
};

包含可訪問資源庫的任何可訪問索引器均可以用做對象初始值設定項中的表達式之一,這與參數的數量或類型無關。 索引參數構成左側賦值,而表達式右側是值。 例如,若是 IndexersExample 具備適當的索引器,則這些都是有效的:ide

var thing = new IndexersExample {
    name = "object one",
    [1] = '1',
    [2] = '4',
    [3] = '9',
    Size = Math.PI,
    ['C',4] = "Middle C"
}

對於要進行編譯的前面的代碼,IndexersExample 類型必須具備如下成員:函數

public string name;
public double Size { set { ... }; }
public char this[int i] { set { ... }; }
public string this[char c, int i] {  set { ... }; }
 
具備匿名類型的對象初始值設定項
儘管對象初始值設定項可用於任何上下文中,但它們在 LINQ 查詢表達式中特別有用。 查詢表達式常使用只能經過使用對象初始值設定項進行初始化的匿名類型,以下面的聲明所示。
var pet = new { Age = 10, Name = "Fluffy" };

利用匿名類型,LINQ 查詢表達式中的 select 子句能夠將原始序列的對象轉換爲其值和形狀可能不一樣於原始序列的對象。 若是你只想存儲某個序列中每一個對象的部分信息,則這頗有用。 在下面的示例中,假定產品對象 (p) 包含不少字段和方法,而你只想建立包含產品名和單價的對象序列。ui

var productInfos =
    from p in products
    select new { p.ProductName, p.UnitPrice };

執行此查詢時,productInfos 變量將包含一系列對象,這些對象能夠在 foreach 語句中進行訪問,以下面的示例所示:this

foreach(var p in productInfos){...}

新的匿名類型中的每一個對象都具備兩個公共屬性,這兩個屬性接收與原始對象中的屬性或字段相同的名稱。 你還可在建立匿名類型時重命名字段;下面的示例將 UnitPrice 字段重命名爲 Pricespa

select new {p.ProductName, Price = p.UnitPrice};
 
集合初始值設定項

在初始化實現 IEnumerable 的集合類型和初始化使用適當的簽名做爲實例方法或擴展方法的 Add 時,集合初始值設定項容許指定一個或多個元素初始值設定項。 元素初始值設定項能夠是簡單的值、表達式或對象初始值設定項。 經過使用集合初始值設定項,無需指定多個調用;編譯器將自動添加這些調用。code

下面的示例演示了兩個簡單的集合初始值設定項:

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };

下面的集合初始值設定項使用對象初始值設定項來初始化上一個示例中定義的 Cat 類的對象。 請注意,各個對象初始值設定項分別括在大括號中且用逗號隔開。

List<Cat> cats = new List<Cat>
{
    new Cat{ Name = "Sylvester", Age=8 },
    new Cat{ Name = "Whiskers", Age=2 },
    new Cat{ Name = "Sasha", Age=14 }
};

若是集合的 Add 方法容許,則能夠將 null 指定爲集合初始值設定項中的一個元素。

List<Cat> moreCats = new List<Cat>
{
    new Cat{ Name = "Furrytail", Age=5 },
    new Cat{ Name = "Peaches", Age=4 },
    null
};

若是集合支持讀取/寫入索引,能夠指定索引元素。

var numbers = new Dictionary<int, string>
{
    [7] = "seven",
    [9] = "nine",
    [13] = "thirteen"
};

前面的示例生成調用 Item[TKey] 以設置值的代碼。 從 C# 6 開始,可使用如下語法初始化字典和其餘關聯容器。 請注意,它使用具備多個值的對象,而不是帶括號和賦值的索引器語法:

var moreNumbers = new Dictionary<int, string>
{
    {19, "nineteen" },
    {23, "twenty-three" },
    {42, "forty-two" }
};

示例

下例結合了對象和集合初始值設定項的概念。

 1 public class InitializationSample
 2 {
 3     public class Cat
 4     {
 5         // 自動屬性
 6         public int Age { get; set; }
 7         public string Name { get; set; }
 8 
 9         public Cat() { }
10 
11         public Cat(string name)
12         {
13             Name = name;
14         }
15     }
16 
17     public static void Main()
18     {
19         Cat cat = new Cat { Age = 10, Name = "Fluffy" };
20         Cat sameCat = new Cat("Fluffy"){ Age = 10 };
21 
22         List<Cat> cats = new List<Cat>
23         {
24             new Cat { Name = "Sylvester", Age = 8 },
25             new Cat { Name = "Whiskers", Age = 2 },
26             new Cat { Name = "Sasha", Age = 14 }
27         };
28 
29         List<Cat> moreCats = new List<Cat>
30         {
31             new Cat { Name = "Furrytail", Age = 5 },
32             new Cat { Name = "Peaches", Age = 4 },
33             null
34         };
35 
36         // 打印結果
37         System.Console.WriteLine(cat.Name);
38 
39         foreach (Cat c in cats)
40             System.Console.WriteLine(c.Name);
41 
42         foreach (Cat c in moreCats)
43             if (c != null)
44                 System.Console.WriteLine(c.Name);
45             else
46                 System.Console.WriteLine("List element has null value.");
47     }
48     // 輸出:
49     //Fluffy
50     //Sylvester
51     //Whiskers
52     //Sasha
53     //Furrytail
54     //Peaches
55     //List element has null value.
56 }

下面的示例展現了實現 IEnumerable 且包含具備多個參數的 Add 方法的一個對象,它使用在列表中每項具備多個元素的集合初始值設定項,這些元素對應於 Add 方法的簽名。

 1 public class FullExample
 2     { 
 3         class FormattedAddresses : IEnumerable<string>
 4         {
 5             private List<string> internalList = new List<string>();
 6             public IEnumerator<string> GetEnumerator() => internalList.GetEnumerator();
 7 
 8             System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => internalList.GetEnumerator();
 9 
10             public void Add(string firstname, string lastname, 
11                 string street, string city, 
12                 string state, string zipcode) => internalList.Add(
13                 $@"{firstname} {lastname}
14                    {street}
15                    {city}, {state} {zipcode}"
16                 );
17         }
18 
19         public static void Main()
20         {
21             FormattedAddresses addresses = new FormattedAddresses()
22             {
23                 {"John", "Doe", "123 Street", "Topeka", "KS", "00000" },
24                 {"Jane", "Smith", "456 Street", "Topeka", "KS", "00000" }
25             };
26 
27             Console.WriteLine("Address Entries:");
28 
29             foreach (string addressEntry in addresses)
30             {
31                 Console.WriteLine("\r\n" + addressEntry);
32             }
33         }
34 
35         /*
36          * 輸出:
37          
38             Address Entries:
39 
40             John Doe
41             123 Street
42             Topeka, KS 00000
43 
44             Jane Smith
45             456 Street
46             Topeka, KS 00000
47          */
48     }

Add 方法可以使用 params 關鍵字來獲取可變數量的自變量,以下例中所示。 此示例還演示了索引器的自定義實現,以使用索引初始化集合。

  1 public class DictionaryExample
  2 { 
  3     class RudimentaryMultiValuedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, List<TValue>>>
  4     {
  5         private Dictionary<TKey, List<TValue>> internalDictionary = new Dictionary<TKey, List<TValue>>();
  6 
  7         public IEnumerator<KeyValuePair<TKey, List<TValue>>> GetEnumerator() => internalDictionary.GetEnumerator();
  8 
  9         System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => internalDictionary.GetEnumerator();
 10 
 11         public List<TValue> this[TKey key]
 12         {
 13             get => internalDictionary[key];
 14             set => Add(key, value);
 15         }
 16 
 17         public void Add(TKey key, params TValue[] values) => Add(key, (IEnumerable<TValue>)values);
 18 
 19         public void Add(TKey key, IEnumerable<TValue> values)
 20         {
 21             if (!internalDictionary.TryGetValue(key, out List<TValue> storedValues))
 22                 internalDictionary.Add(key, storedValues = new List<TValue>());
 23 
 24             storedValues.AddRange(values);
 25         }
 26     }
 27 
 28     public static void Main()
 29     {
 30         RudimentaryMultiValuedDictionary<string, string> rudimentaryMultiValuedDictionary1
 31             = new RudimentaryMultiValuedDictionary<string, string>()
 32             {
 33                 {"Group1", "Bob", "John", "Mary" },
 34                 {"Group2", "Eric", "Emily", "Debbie", "Jesse" }
 35             };
 36         RudimentaryMultiValuedDictionary<string, string> rudimentaryMultiValuedDictionary2
 37             = new RudimentaryMultiValuedDictionary<string, string>()
 38             {
 39                 ["Group1"] = new List<string>() { "Bob", "John", "Mary" },
 40                 ["Group2"] = new List<string>() { "Eric", "Emily", "Debbie", "Jesse" }
 41             };
 42         RudimentaryMultiValuedDictionary<string, string> rudimentaryMultiValuedDictionary3
 43             = new RudimentaryMultiValuedDictionary<string, string>()
 44             {
 45                 {"Group1", new string []{ "Bob", "John", "Mary" } },
 46                 { "Group2", new string[]{ "Eric", "Emily", "Debbie", "Jesse" } }
 47             };
 48 
 49         Console.WriteLine("Using first multi-valued dictionary created with a collection initializer:");
 50 
 51         foreach (KeyValuePair<string, List<string>> group in rudimentaryMultiValuedDictionary1)
 52         {
 53             Console.WriteLine($"\r\nMembers of group {group.Key}: ");
 54 
 55             foreach (string member in group.Value)
 56             {
 57                 Console.WriteLine(member);
 58             }
 59         }
 60 
 61         Console.WriteLine("\r\nUsing second multi-valued dictionary created with a collection initializer using indexing:");
 62 
 63         foreach (KeyValuePair<string, List<string>> group in rudimentaryMultiValuedDictionary2)
 64         {
 65             Console.WriteLine($"\r\nMembers of group {group.Key}: ");
 66 
 67             foreach (string member in group.Value)
 68             {
 69                 Console.WriteLine(member);
 70             }
 71         }
 72         Console.WriteLine("\r\nUsing third multi-valued dictionary created with a collection initializer using indexing:");
 73 
 74         foreach (KeyValuePair<string, List<string>> group in rudimentaryMultiValuedDictionary3)
 75         {
 76             Console.WriteLine($"\r\nMembers of group {group.Key}: ");
 77 
 78             foreach (string member in group.Value)
 79             {
 80                 Console.WriteLine(member);
 81             }
 82         }
 83     }
 84 
 85     /*
 86      * 輸出:
 87      
 88         Using first multi-valued dictionary created with a collection initializer:
 89 
 90         Members of group Group1:
 91         Bob
 92         John
 93         Mary
 94 
 95         Members of group Group2:
 96         Eric
 97         Emily
 98         Debbie
 99         Jesse
100 
101         Using second multi-valued dictionary created with a collection initializer using indexing:
102 
103         Members of group Group1:
104         Bob
105         John
106         Mary
107 
108         Members of group Group2:
109         Eric
110         Emily
111         Debbie
112         Jesse
113 
114         Using third multi-valued dictionary created with a collection initializer using indexing:
115 
116         Members of group Group1:
117         Bob
118         John
119         Mary
120 
121         Members of group Group2:
122         Eric
123         Emily
124         Debbie
125         Jesse
126      */
127 }

 

相關文章
相關標籤/搜索