col*_*mde 17 c# automatic-properties
我有一个目前自动的财产.
public string MyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是,我现在需要它在每次更改时执行一些操作,所以我想为setter添加逻辑.所以我想做一些事情:
public string MyProperty {
get;
set { PerformSomeAction(); }
}
Run Code Online (Sandbox Code Playgroud)
但是,这不构建...... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial
我不能只让getter返回,MyProperty因为它会导致无限循环.
有没有办法做到这一点,还是我必须声明一个私有变量来引用?我宁愿不要MyProperty在这个类和它之外的代码中使用它
Mar*_*ius 17
您需要使用具有支持字段的属性:
private string mMyProperty;
public string MyProperty
{
get { return mMyProperty; }
set
{
mMyProperty = value;
PerformSomeAction();
}
}
Run Code Online (Sandbox Code Playgroud)
您不能一无所有地实现,因为当使用一个时,它指的是(自动生成的属性的情况下自动生成的)(隐藏的)后备字段。但是,当您实现一个时,您必须同时设置两种背景。
自动方式只是实现此目的的捷径:
private string _property;
public string MyProperty
{
get { return _property; }
set { _property = value; }
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您要在其中一种方法中忽略隐藏字段(这实际上是getter和setter的意思),那么该方法应该如何知道如何存储/获取值?
| 归档时间: |
|
| 查看次数: |
5686 次 |
| 最近记录: |