为什么我可以将初始化器语法与只读属性一起使用 [英] Why can I use initializer syntax with readonly properties

查看:72
本文介绍了为什么我可以将初始化器语法与只读属性一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个属性的 Manager 类:

I have a Manager class with two properties as below:

public class Manager()
{
  private string _name;
  private List<int> _reportingEmployeesIds;
  public string Name { get { return _name; }}
  public List<int> ReportingEmployeesIds { get {return _reportingEmployeesIds; } }  

我正在尝试如下创建 Manager 类的实例

I am trying to create an instance of the Manager class as follows

Manager m = new Manager 
{  
   Name = "Dave", // error, expected
   ReportingEmployeesIds = {2345, 432, 521} // no compile error - why?
};

两个属性都缺少set属性,但是编译器允许设置 ReportingEmployeesIds ,而不允许设置Name属性(错误:Property或indexer Manager.Name不能分配给它,只读).

The set property is missing from both the properties but the compiler allows setting ReportingEmployeesIds whereas does not allow setting the Name property (Error: Property or indexer Manager.Name can not be assigned to, it is readonly).

为什么会这样?为何编译器不会抱怨 ReportingEmployeesIds 是只读的.

Why is this the case? Why doesn't the compiler complain about the ReportingEmployeesIds being readonly.

推荐答案

ReportingEmployeesIds = {2345,432,521} 设置该属性.这是对每个项目调用 Add(...)的简写.即使对于只读列表属性,您也可以始终 Add .

The ReportingEmployeesIds = {2345, 432, 521} doesn't set the property. It is shorthand for calling Add(...) with each of the items. You can always Add, even for a readonly list property.

要成为一个 set ,它必须是:

For it to be a set it would need to be:

ReportingEmployeesIds = new List<int> {2345, 432, 521}

相反,该行:

Manager m = new Manager {Name = "Dave", ReportingEmployeesIds = {2345, 432, 521} }

本质上是:

var m = new Manager();
m.Name = "Dave";
var tmp = m.ReportingEmployeesIds;
tmp.Add(2345);
tmp.Add(432);
tmp.Add(521);

这篇关于为什么我可以将初始化器语法与只读属性一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆