zoukankan      html  css  js  c++  java
  • [原创]c# 类中 Collection 字段初始化的特殊之处

    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类型的字段,才可能如此!

    如果有知道的朋友,麻烦告知我为什么.

  • 相关阅读:
    计算机图形学
    2017.3.20
    史上最强型人养成秘籍: 90 天肥仔变型男实录
    Word 2013发布博客测试
    eeeeeeeeeee
    测试,使用word2013发布博客园博客
    Win7系统桌面便签怎么添加?
    开启两步验证的教程
    【Todo】 cygwin下emacs中M-x shell 中出现乱码
    emacs的LoadPath
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/8394696.html
Copyright © 2011-2022 走看看