1. 程式人生 > >[C#.NET 拾遺補漏]03:你可能不知道的幾種物件初始化方式

[C#.NET 拾遺補漏]03:你可能不知道的幾種物件初始化方式

閱讀本文大概需要 1.2 分鐘。

隨著 C# 的升級,C# 在語法上對物件的初始化做了不少簡化,來看看有沒有你不知道的。

陣列的初始化

在上一篇羅列陣列的小知識的時候,其中也提到了陣列的初始化,這時直接引用過來。

int[] arr = new int[3] {1, 2, 3}; // 正兒八經的初始化
int[] arr = new [] {1, 2, 3}; // 簡化掉了 int 和陣列容量宣告
int[] arr = {1, 2, 3}; // 終極簡化

字典的兩種初始化方式

第二種是 C# 6 的語法,可能很多人不知道。

// 方式一:
var dict = new Dictionary<string, int>
{
{ "key1", 1 },
{ "key2", 20 }
};

// 方式二:
var dict = new Dictionary<string, int>
{
["key1"] = 1,
["key2"] = 20
};

含自定義索引器的物件初始化

這種初始化原理上其實是和上面字典的第二種初始化是一樣的。

public class IndexableClass
{
public int this[int index]
{
set
{
Console.WriteLine("{0} was assigned to index {1}", value, index);
}
}
}

var foo = new IndexableClass
{
[0] = 10,
[1] = 20
}

元組(Tuple)的三種初始化方式

前面兩種方式很常見,後面一種是 C# 7 的語法,可能有些人不知道。

// 方式一:
var tuple = new Tuple<string, int, MyClass>("foo", 123, new MyClass());

// 方式二:
var tuple = Tuple.Create("foo", 123, new MyClass());

// 方式三:
var tuple = ("foo", 123, new MyClass());

另外補充個小知識,在 C# 7 中,元組的元素可以被解構命名:

(int number, bool flage) tuple = (123, true);
Console.WriteLine(tuple.number); // 123
Console.WriteLine(tuple.flag); // True

自定義集合類的初始化

只要自定義集合類包含Add方法,便可以使用下面這種初始化方式為集合初始化元素。

class Program
{
static void Main()
{
var collection = new MyCollection {
"foo", // 對應方法:Add(string item)
{ "bar", 3 }, // 對應方法:Add(string item, int count)
"baz", // 對應方法:Add(string item)
123.45d, // 對應擴充套件方法:Add(this MyCollection @this, double value)
};
}
}

class MyCollection : IEnumerable
{
privatereadonly IList _list = new ArrayList();

public void Add(string item)
{
_list.Add(item);
}

public void Add(string item, int count)
{
for (int i = 0; i < count; i++)
{
_list.Add(item);
}
}

public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
}

static class MyCollectionExtensions
{
public static void Add(this MyCollection @this, double value) =>
@this.Add(value.ToString());
}

物件的集合屬性初始化

我們知道對集合的初始化必須使用new建立該集合,不能省略,比如:

// OK
IList<string> synonyms = new List<string> { "c#", "c-sharp" };

// 編譯報錯,不能省略 new List<string>
IList<string> synonyms = { "c#", "c-sharp" };

但如果該集合作為另外一個類的屬性,則可以省略new,比如:

public class Tag
{
public IList<string> Synonyms { get; set; }
}

var tag = new Tag
{
Synonyms = { "c#", "c-sharp" } // OK
};

能想到和找到的就這麼點了,希望以上會對你的程式設計有所幫助。