没有身体的吸气剂,有的塞特 [英] Getter without body, Setter with

查看:76
本文介绍了没有身体的吸气剂,有的塞特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目前是自动的属性.

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屋!

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