[C#6] 7-索引初始化器
0. 目录
1. 老版本的代码
private static void Main()
{
var dictionary = new Dictionary<int, string> {
{ , "Value1" },
{ , "Value2" },
{ , "Value3" }
};
}
早C#3中引入的集合初始化器,可是让我们用上面的语法来在声明一个字典或者集合的时候立即初始化一些项进去,其实在C#3中这是个语法糖,实质编译后的结果是调用字典或者集合的Add方法逐一添加这些项。但是有一点小小的不直观。先看看这个版的IL吧:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 47 (0x2f)
.maxstack
.locals init ([] class [mscorlib]System.Collections.Generic.Dictionary`<int32,string> dictionary)
IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::.ctor()
IL_0006: dup
IL_0007: ldc.i4.
IL_0008: ldstr "Value1"
IL_000d: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::Add(!,
!)
IL_0012: nop
IL_0013: dup
IL_0014: ldc.i4.
IL_0015: ldstr "Value2"
IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::Add(!,
!)
IL_001f: nop
IL_0020: dup
IL_0021: ldc.i4.
IL_0022: ldstr "Value3"
IL_0027: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::Add(!,
!)
IL_002c: nop
IL_002d: stloc.
IL_002e: ret
} // end of method Program::Main
本质是Add方法的调用.C#6引入了一种新语法来进一步的优化这种写法。
2. 索引初始化器
private static void Main()
{
var dictionary = new Dictionary<int, string>
{
[] = "Value1",
[] = "Value2",
[] = "Value3"
};
}
看起来直观许多了吧,其实是一种语法改进。编译结果也有些许差异,如下:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 47 (0x2f)
.maxstack
.locals init ([] class [mscorlib]System.Collections.Generic.Dictionary`<int32,string> dictionary)
IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::.ctor()
IL_0006: dup
IL_0007: ldc.i4.
IL_0008: ldstr "Value1"
IL_000d: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::set_Item(!,
!)
IL_0012: nop
IL_0013: dup
IL_0014: ldc.i4.
IL_0015: ldstr "Value2"
IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::set_Item(!,
!)
IL_001f: nop
IL_0020: dup
IL_0021: ldc.i4.
IL_0022: ldstr "Value3"
IL_0027: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`<int32,string>::set_Item(!,
!)
IL_002c: nop
IL_002d: stloc.
IL_002e: ret
} // end of method Program::Main
主要差异在于老语法是调用Add方法,新语法是用的索引器的set访问器(set_Item)。
既然是索引,那么就索引就不仅仅只能是int,也可以是string,任意的自定义类型。
3. Example
namespace csharp6
{
internal class Program
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; } private Dictionary<string, Address> _cache = new Dictionary<string, Address>(); public Address this[string name]
{
get { return _cache[name]; }
set { _cache[name] = value; }
}
} public class Address
{
public string Name { get; set; }
public string Zip { get; set; }
} private static void Main()
{
//string索引
var colorMap = new Dictionary<string, ConsoleColor>
{
["Error"] = ConsoleColor.Red,
["Information"] = ConsoleColor.Yellow,
["Verbose"] = ConsoleColor.White
}; //枚举索引
var colors = new Dictionary<ConsoleColor, string>
{
[ConsoleColor.Red] = "#F00",
[ConsoleColor.Green] = "#0F0",
}; //自定义类型的索引器支持
Person person = new Person
{
Name = "blackheart",
Age = ,
["home"] = new Address { Name = "北京市", Zip = "" },
["work"] = new Address { Name = "南京市", Zip = "" }
}; //自定义类型索引
var persons = new Dictionary<Person, List<Address>>
{
[new Person { Name = "blackheart", Age = }] = new List<Address> {
new Address { Name = "北京市", Zip = "" }
},
[new Person { Name = "blackheart", Age = }] = new List<Address> {
new Address { Name = "南京市", Zip = "" }
},
};
}
}
}
4. 总结
从本质来看,[xxx]=yyy这种语法,xxx可以是任意类型,凡是有索引器支持的类型,均可以使用这种语法。简单直接明了。
[C#6] 7-索引初始化器的更多相关文章
- .NET中那些所谓的新语法之一:自动属性、隐式类型、命名参数与自动初始化器
开篇:在日常的.NET开发学习中,我们往往会接触到一些较新的语法,它们相对以前的老语法相比,做了很多的改进,简化了很多繁杂的代码格式,也大大减少了我们这些菜鸟码农的代码量.但是,在开心欢乐之余,我们也 ...
- Linq之隐式类型、自动属性、初始化器、匿名类
目录 写在前面 系列文章 隐式类型 自动属性 初始化器 匿名类 总结 写在前面 上篇文章是本系列的小插曲,也是在项目中遇到,觉得有必要总结一下,就顺手写在了博客中,也希望能帮到一些朋友.本文将继续介绍 ...
- C#高级知识点概要(3) - 特性、自动属性、对象集合初始化器、扩展方法、Lambda表达式和Linq查询
1.特性(Attributes) 特性(Attributes),MSDN的定义是:公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型.字段.方法 ...
- .NET 中创建支持集合初始化器的类型
对象初始化器和集合初始化器只是语法糖,但是能让你的代码看起来更加清晰.至少能让对象初始化的代码和其他业务执行的代码分开,可读性会好一些. 本文将编写一个类型,可以使用集合初始化器构造这个类型.不只是添 ...
- C#_基础,初始化器
对象初始化器 在没有对象初始化器之前,我们创建一个对象大概需要经过这么两个步骤,首先new一个对象,然后给每个字段赋值.而有了对象初始化器之后,原本需要几行代码才能完成的任务变成一行代码就可以完成,简 ...
- 6.Swift协议|扩展|访问权限|异常调试|类型转换|运算函数|ARC|类类型初试化器|值类型初始化器
1. 协议(Protocol):与OC之间唯一不同的是Swift中的协议不管是属性还时方法全部是必须实现的 /** protocol*/ protocol FullNamed { /** 计算属性申明 ...
- swift_初始化器的使用
//: Playground - noun: a place where people can play import Cocoa ***************************结构体与Cla ...
- Linq专题之集合初始化器
集合初始化器用来初始化一个集合,和对象初始化器有点类似,都是用一对{}来初始化. using System; using System.Collections.Generic; using Syste ...
- Linq专题之对象初始化器
在C#3.0之前,如果创建一个新的对象,往往需要调用类的构造函数来初始化该对象的值,在c#3.0提供了一个"对象初始化器"的机制,使得开发人员在创建新的对象时不通过调用类的构造函数 ...
随机推荐
- 解决Oracle SQL Developer无法连接远程服务器的问题
在使用Oracle SQL Developer连接远程服务器的时候,出现如下的错误 在服务器本地是可以正常连接的.这个让人想起来,跟SQL Server的一些设计有些类似,服务器估计默认只在本地监听, ...
- 窥探Swift系列博客说明及其Swift版本间更新
Swift到目前为止仍在更新,每次更新都会推陈出新,一些Swift旧版本中的东西在新Swift中并不适用,而且新版本的Swift会添加新的功能.到目前为止,Swift为2.1版本.去年翻译的Swift ...
- 升级 Visual Studio 2015 CTP 5 的坑、坑、坑
前两天,微软发布了 Visual Studio 2015 CTP 5,全称为 Visual Studio 2015 Community Technology Preview 5,意为社区技术预览版,之 ...
- 第一章 Linux內核簡介
1. Linux是類Unix系統,但他不是Unix. 儘管Linux借鑑了Unix的許多設計並且實現了Unix的API(由Posix標準和其他Single Unix Specification定義的) ...
- 再看ftp上传文件
前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...
- c++之字符型中的特殊字符回车符
1.字符型的应用之强制类型转换: #include<iostream> using namespace std; int main() { ;i<;i++) { cout<&l ...
- centos-5.5安装vmvare tools
centos-5.5安装vmvare tools 虚拟机管理,安装tools 找到VMwareTools压缩包 解压到Desktop,桌面 终端进入桌面 执行程序# ./vmware-install. ...
- CQRS, Task Based UIs, Event Sourcing agh!
原文地址:CQRS, Task Based UIs, Event Sourcing agh! Many people have been getting confused over what CQRS ...
- SQL Server 2014里的性能提升
在这篇文章里我想小结下SQL Server 2014引入各种惊艳性能提升!! 缓存池扩展(Buffer Pool Extensions) 缓存池扩展的想法非常简单:把页文件存储在非常快的存储上,例如S ...
- 微信小程序:原生热布局终将改变世界
关于本文的所有观点都是网上收集,与作者本人没有任何关系! 最近朋友圈已经被微信小程序刷屏了,这也难怪,腾讯的产品拥有广泛的影响力,谁便推出个东西,都会有很多人认为会改变世界,这不,张小龙刚一发布微信小 ...