为什么自动属性需要 getter 和 setter?
在 C# 中,如果我声明一个自动实现的属性,为什么我必须同时声明 get 和 set 部分?
即
public string ThisWorks { get; set; }
public string ThisDoesnt { get; }
,这不是只是语法糖吗?即编译器为属性插入一个私有字段? 那么为什么会出现这个问题呢?
好奇的。
In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part?
i.e.
public string ThisWorks { get; set; }
public string ThisDoesnt { get; }
Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?
Curious.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您没有设置器 - 那么您将如何设置该属性?
顺便说一句,您可以指定可访问性,例如:
If you didn't have a setter - then how would you ever set the property?
Incidentally, you can specify the accessibility, eg:
如果没有设置器,您将永远无法提供值 - 因为您没有任何方法来指定支持变量的名称。
我请求了一个只读自动属性,声明如下:
它将创建一个只读支持变量,一个只有 getter 的属性,并将对 setter 的所有调用转换为对变量的直接访问。 您只能在构造函数中调用 setter - 就像普通的只读变量一样。
我们将看看这个请求是否有任何好处......目前它不在那里真是太遗憾了,因为它使得实现不可变类型比实现可变类型更困难:(
Without a setter, you would never be able to provide a value - as you don't have any way of specifying the backing variable's name.
I've requested a readonly automatic property, declared like this:
which would create a readonly backing variable, a property with only a getter, and translate all calls to the setter into direct access to the variable. You could only call the setter within the constructor - just like for normal readonly variables.
We'll see whether this request does any good... it's a real shame it's not in there at the moment, as it makes it harder to implement immutable types than mutable types :(
自动实现的属性没有可访问的私有存储,因此如果没有设置器,您将无法设置该值,从而使其完全无用。
An auto-implemented property has no accessible private store, so you would have no way to set the value without a setter, making it totally useless.
您需要一个集合 - 否则,您的自动实现的属性如何获取其值? 自动实现属性时,您必须有一个 set 访问器,至少在构造过程中为其赋予一个值。
You need a set - otherwise, how does your auto-implemented property get its value? When auto-implementing the property, you have to have a set accessor to at least give it a value during construction.
有趣的是,即使项目配置为使用 C# 版本 5,Visual Studio 2015 中的新 Roslyn 编译器现在也允许这样做。
Interestingly, the new Roslyn compiler in Visual Studio 2015 now allows this, even if the project is configured to use C# version 5.