// C# 3.0 支持的语法。集合初始项 Dictionary<string, string> builtInDataTypes = new Dictionary<string, string>() { {"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<int, string> { [10] = "main() {", [20] = " printf(\"hello, world\")", [30] = "}" }; // 以下的写法是错误的。不可以同时使用两种方式 var errorDic = new Dictionary<int, string> { {"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<int, string> { $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 类型
C# 6.0 (C# vNext) 新功能之:Indexed Members and Element Initializers 索引的成员和元素初始化
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.