没有身体的吸气剂,有的塞特 [英] Getter without body, Setter with
问题描述
我有一个目前是自动的属性.
I have a property which is currently automatic.
public string MyProperty { get; set; }
但是,我现在需要它在每次更改时执行一些操作,因此我想向设置器添加逻辑.所以我想做类似的事情:
However, I now need it to perform some action every time it changes, so I want to add logic to the setter. So I want to do something like:
public string MyProperty {
get;
set { PerformSomeAction(); }
}
但是,这不会建立... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial
However, this doesn't build... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial
我不能只让吸气剂返回MyProperty
,因为它会导致无限循环.
I can't just have the getter return MyProperty
as it will cause an infinite loop.
有没有办法做到这一点,还是我必须声明一个私有变量来引用?我宁愿不使用MyProperty
来遍历该类及其外部的代码
Is there a way of doing this, or do I have to declare a private variable to refer to? I'd rather not as MyProperty
is used through out the code both in this class and outside it
推荐答案
您需要使用带有后备字段的属性:
You need to use a property with backing field:
private string mMyProperty;
public string MyProperty
{
get { return mMyProperty; }
set
{
mMyProperty = value;
PerformSomeAction();
}
}
这篇关于没有身体的吸气剂,有的塞特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!