C# 二十五、匿名型別與物件初始化器(附帶:類初始化器)
阿新 • • 發佈:2018-12-20
- 匿名型別提供了一種方便的方法,可用來將一組只讀屬性封裝到單個物件中,而無需首先顯式定義一個型別。
- 型別名由編譯器生成,並且不能在原始碼級使用。
- 每個屬性的型別由編譯器推斷。
- 可通過使用new運算子和物件初始值建立匿名型別。
- 匿名型別包含一個或多個公共只讀屬性。
- 包含其他種類的類成員(如方法或事件)為無效。
- 用來初始化屬性的表示式不能為
null
、匿名函式或指標型別。 - 通常,當使用匿名型別來初始化變數時,可以通過使用var將變數作為隱式鍵入的本地變數來進行宣告。
- 匿名型別是直接從物件派生的類型別,並且其無法強制轉換為除物件外的任意型別。
var v = new { theName = "jpf", theAge = 24, theSex='M' }; Console.WriteLine("姓名:{0},年齡:{1},性別:{2}。",v.theName,v.theAge,v.theSex); ---> 姓名:jpf,年齡:24,性別:M。
- 可通過將隱式鍵入的本地變數與隱式鍵入的陣列相結合建立匿名鍵入的元素的陣列。
var arr = new[]{ new { theName = "jpfa", theAge = 24 }, new { theName = "jpfb", theAge = 25 } };
foreach (var item in arr)
{
Console.WriteLine(item);
}
--->
{ theName = jpfa, theAge = 24 }
{ theName = jpfb, theAge = 25 }
官方文件:
類初始化器
class Game { private string _theName; public string TheName { get { return _theName; } set { _theName = value; } } private char _theSex; public char TheSex { get { return _theSex; } set { _theSex = value; } } private int _theAge; public int TheAge { get { return _theAge; } set { _theAge = value; } } }
class Program { static void Main(string[] args) { Game game = new Game() { TheName = "jpf", TheAge = 24, TheSex = 'M' }; Console.WriteLine("姓名:{0},年齡:{1},性別:{2}。", game.TheName, game.TheAge, game.TheSex); Console.ReadKey(); } } ---> 姓名:jpf,年齡:24,性別:M。