码迷,mamicode.com
首页 > Windows程序 > 详细

Object and Collection Initializers (C# Programming Guide) 类初始化

时间:2019-11-28 12:59:26      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:nts   The   image   prope   dex   mat   gui   enum   auto   

public class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } public Cat() { } public Cat(string name) { this.Name = name; } }

 

 技术图片

 

 

 

技术图片

 

 

 

var moreNumbers = new Dictionary<int, string>
{
{19, "nineteen" },
{23, "twenty-three" },
{42, "forty-two" }
};

 

技术图片

 

 

Starting with C# 6, object initializers can set indexers, in addition to assigning fields and properties. Consider this basic Matrix class:

public class Matrix {

private double[,] storage = new double[3, 3];

public double this[int row, int column] { // The embedded array will throw out of range exceptions as appropriate. get { return storage[row, column]; } set { storage[row, column] = value; } } }

 

var identity = new Matrix { [0, 0] = 1.0, [0, 1] = 0.0, [0, 2] = 0.0, [1, 0] = 0.0, [1, 1] = 1.0, [1, 2] = 0.0, [2, 0] = 0.0, [2, 1] = 0.0, [2, 2] = 1.0, };

 

这个有意思:就是用lambda 表达式来初始化类

技术图片

 

 


public static void Main() { FormattedAddresses addresses = new FormattedAddresses() { {"John", "Doe", "123 Street", "Topeka", "KS", "00000" }, {"Jane", "Smith", "456 Street", "Topeka", "KS", "00000" } }; Console.WriteLine("Address Entries:"); foreach (string addressEntry in addresses) { Console.WriteLine("\r\n" + addressEntry); } } /* * Prints: Address Entries: John Doe 123 Street Topeka, KS 00000 Jane Smith 456 Street Topeka, KS 00000 */ }

Object and Collection Initializers (C# Programming Guide) 类初始化

标签:nts   The   image   prope   dex   mat   gui   enum   auto   

原文地址:https://www.cnblogs.com/gaoxianzhi/p/11948914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!