在C#中自动实现的属性属性

2023-09-03 12:14:20 作者:暴走的小菇凉

有没有办法继续利用自动实现的属性,同时还养了改变事件,如 INotifyPropertyChanged的,当设置被称为?

Is there a way to continue to utilise auto-implemented properties while still raising a change event, such as INotifyPropertyChanged, when Set is called?

相反的:

private string _value;
public string Value
{
  get 
  { 
    return this._value;
  }
  set
  {
    this._value = value;
    this.ValueChanged(this,EventArgs.Empty);
  }
}

可我只是做:

Can I just do:

public string Value 
{ 
   get; 
   set 
   { 
     this.ValueChanged(this,EventArgs.Empty); 
   }
}

尽管制定者看起来错误的,是有可能做到这一点不与后备存储变量填充我的课?

Although the setter looks wrong, is it possible to do this without filling my class with backing-store variables?

更新:看起来像有没有标准的解决方案,我懒的目标,我认为最好的解决方法是使用$ C $挤压或ReSharper的生成我所有的后备存储为我

UPDATE: Looks like there is no standard solution to my lazy objective, I think that the best solution is to use CodeRush or Resharper to generate all my backing stores for me.

推荐答案

您无法做到这一点。该规范自动实现的属性是pretty的明确的:

You can't do this. The specification for automatically implemented properties is pretty clear:

自动实施   (自动实现的)性能自动化   这种模式。进一步来说,   非抽象属性声明是   允许有分号访问   机构。两个访问必须是present   两者必须有分号机构,   但它们可以有不同的   访问修饰符。当一个   属性指定这样的,一   支持字段将自动   为属性生成以及   存取器将被实现为读   和写入的支持字段。   支持字段的名称是   编译器生成,无法访问   该用户。

Automatically implemented (auto-implemented) properties automate this pattern. More specifically, non-abstract property declarations are allowed to have semicolon accessor bodies. Both accessors must be present and both must have semicolon bodies, but they can have different accessibility modifiers. When a property is specified like this, a backing field will automatically be generated for the property, and the accessors will be implemented to read from and write to that backing field. The name of the backing field is compiler generated and inaccessible to the user.

在换句话说,他们只能有搞定; 设置; ,并有可能的访问修饰符。

In other words, they can only have "get;" and "set;", with the possibility of access modifiers.