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类型的字段,才可能如此!
如果有知道的朋友,麻烦告知我为什么.