关于获取的问题;放;
当我更改其中一个类属性时,我想设置一个修改标志,如下所示,
public bool Modified { get; set; }
public bool Enabled { get; set { Modified = true; } }
问题是我有一个错误,编译器要求我为 get 声明一个主体; 我宁愿不必声明一个单独的私有变量,是否有其他方法可以做到这一点。
c#, ,net-2
谢谢
I would like to set a modified flag when ever I change one of the class properties as shown below
public bool Modified { get; set; }
public bool Enabled { get; set { Modified = true; } }
problem is I have an error and the compiler is asking me to declare a body for the get;
I would rather not have to declare a separate private variable, is there another way to do this.
c#, ,net-2
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可以。如果您想要显式的 setter,则不能使用自动 getter。所以你必须有类似的东西:
No. If you want an explicit setter, you can't use an automatic getter. So you must have something like:
这是不可能的。 C# 不允许您为
get
或set
中的一个指定主体,但会自动实现另一个。如果您需要执行此操作,则需要带有支持字段的手动属性。请注意,您想要这样的东西:
This is not possible. C# does not allow you to specify a body for one or the other of
get
orset
but have the other implemented automatically. If you need to do this, you need a manual property with a backing field.Note that you want something like this:
我认为你需要完整地编写 Enabled 的 getter 和 setter:
I think you need to write the getter and setter for Enabled in full:
因为将为
get 创建一个自动生成的成员; set;
属性,那么你就不能声明其中之一,否则你必须自己设置它们since a automatic generated member will be created for
get; set;
property then you cant declare one of them otherwise you have to set them by your own