標籤:customers lis string 理解 new fail collect ati blog
1.今天看一下StackExchange.Redis的原始碼,裡面有這樣一段代碼
public sealed class ConfigurationOptions : ICloneable {...public EndPointCollection EndPoints { get { return this.endpoints; } }... }
調用時是這樣調用的
var option = new ConfigurationOptions() { AbortOnConnectFail = false, EndPoints = {connectionString} };
頓時感覺到詫異,不明白為什麼只有get方法的屬性可以被初始化時賦值,如果是非初始化的賦值是不行的
//option.EndPoints={connectionString}; 這個可以理解,這是編譯不通過的
但是實在不理解為什麼初始化時可以.
於是測試了以下代碼(結果是編譯不通過)
internal class CustomerComponent { private Customer names; public Customer Names { get { return this.names; } } } var customerComponent = new CustomerComponent() { Names = customers[0] };
又測試了下面的(奇蹟出現了,編譯通過了)
internal class CustomerList { private List<string> names; public List<string> Names { get { return this.names; } } } var customerList= new CustomerList() { Names = {"1","2"} };
internal class CustomerList2 { private List<Customer> names; public List<Customer> Names { get { return this.names; } } } var customerList2 = new CustomerList2() { Names = { new Customer() { Name = "G" }, } };
一直不明白為什麼,但是大概總結出來規律, 就是只有Collection類型的欄位,才可能如此!
如果有知道的朋友,麻煩告知我為什麼.
[原創]c# 類中 Collection 欄位初始化的特殊之處