C# 6.0 (C# vNext) 新功能之:Indexed Members and Element Initializers 索引的成員和元素初始化

            // C# 3.0 支持的語法。集合初始項
            Dictionary<stringstring> builtInDataTypes = new Dictionary<stringstring>()
            {
                {"Byte""0 to 255"},
                {"Boolean""True or false."},
                {"Object""An Object."},
                {"String""A string of Unicode characters."},
                {"Decimal""±1.0 × 10e-28 to ±7.9 × 10e28"}
            };
 
            // C# 6.0 新語法,透過索引的方式爲成員初始化
            // 這裹的 int 可以用任何支持  IComparable < T > 的類型代替
            var cppHelloWorldProgram = new Dictionary<intstring>
            {
                [10] = "main() {",
                [20] = "    printf(\"hello, world\")",
                [30] = "}"
            };
            
            // 以下的寫法是錯誤的。不可以同時使用兩種方式
            var errorDic = new Dictionary<intstring>
            {
                {"Byte""0 to 255"},
                {"Boolean""True or false."},
                ["Object"] = "An Object.",
                ["String"] = "A string of Unicode characters.",
                ["Decimal"] = "±1.0 × 10e-28 to ±7.9 × 10e28"
            };
            
            // 新的語法之二
            var newDic = new Dictionary<intstring>
            {
                $Byte = "0 to 255",
                $Boolean = "True or false.",
                $Object = "An Object.",
                $String = "A string of Unicode characters.",
                $Decimal = "±1.0 × 10e-28 to ±7.9 × 10e28"
            };
                        
            var data = newDic$Byte// 取值, 得到:"0 to 255"
 
            // 注:newDic$Byte 在編譯時,並不會檢查 $Byte 是否存在。
            // 比如: var data = newDic$XYZ , 編譯時,並不會檢查出 newDic["XYZ"] 並不存在
 
            // 這種新語法,特別適合用於處理鬆散結構的資料。例如 xml, json, csv。如下 json 例子
            // 以下使用 Newtonsoft.Json framework
            string jsonText = @"
                {
                  'Byte':  {
                    'Keyword':  'byte',
                    'DotNetClassName':  'Byte',
                    'Description':  'Unsigned integer',
                    'Width':  '8',
                    'Range':  '0 to 255'
                            },
                  'Boolean':  {
                    'Keyword':  'bool',
                    'DotNetClassName':  'Boolean',
                    'Description':  'Logical Boolean type',
                    'Width':  '8',
                    'Range':  'True or false.'
                              },
                }";
 
            JObject jObject = JObject.Parse(jsonText);
            var result = jObject.$Boolean.$Keyword;
            // 得到結果 bool
            // 注:語法二,使用 $ 的方式,鍵值只能使用 String 類型
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章