问题描述
这个问题在this回答。由于无法具有只读属性被提议作为使用领域,而不是性能的潜在原因。
This question came up in the comments of this answer. The inability to have readonly properties was proposed as a potential reason to use fields instead of properties.
例如:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
但是,为什么你就不能这样做呢?
But why can't you just do this?
public int Width { get; readonly set; }
编辑(澄清):您可以实现第一个例子此功能。但是,为什么你不能使用自动实现的属性速记做同样的事情?这也将是凌乱少,因为你不会有直接访问在构造函数中的字段;所有的访问是通过属性。
Edit (clarification): You can achieve this functionality in the first example. But why can't you use the auto-implemented property shorthand to do the same thing? It would also be less messy, since you wouldn't have to directly access the fields in your constructor; all access would be through the property.
推荐答案
由于语言不允许这样做。
Because the language doesn't allow it.
这似乎是一个轻浮的答案:毕竟,语言设计者的可能的已经宣布,如果你使用只读
然后自动物业这将意味着楼市可设定,但只有在构造函数中。
This may seem like a frivolous answer: after all, the language designers could have declared that if you used readonly
on an automatic property then it would mean "the property is settable but only in the constructor".
But features don't come for free. (Eric Gunnerson expresses it as "Every feature starts with minus 100 points.") To implement read-only automatic properties would have required additional compiler effort to support the readonly modifier on a property (it currently applies only to fields), to generate the appropriate backing field and to transform sets
of the property to assignments to the backing field. That's quite a bit of work to support something that the user could do reasonably easily by declaring a readonly backing field and writing a one-line property getter, and that work would have a cost in terms of not implementing other features.
所以,颇为重视,得到的答复是,无论是语言的设计者和实施者要么从未想过的想法,或者 - 更容易 - 他们认为这将是不错的,但决定有更好的地方度过有限的资源。有这么prevents语言设计者和提供的功能实施者你建议没有技术限制:原因更多的是关于软件开发的经济学
So, quite seriously, the answer is that either the language designers and implementers either never thought of the idea, or -- more likely -- they thought it would be nice to have, but decided there were better places to spend their finite resources. There's no technical constraint that prevents the language designers and implementers providing the feature you suggest: the reasons are more about the economics of software development.
这篇关于为什么不能属性进行只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!