[原創]c# 類中 Collection 欄位初始化的特殊之處

來源:互聯網
上載者:User

標籤: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 欄位初始化的特殊之處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.