自动实现的属性在C#

当Set被调用时,是否有办法继续使用自动实现的属性,同时仍在引发改变事件,例如INotifyPropertyChanged?

代替:

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

我可以做:

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

虽然setter看起来错了,是否可以这样做,而不用填写我的类与后台存储变量?

更新:看起来我的懒惰目标没有标准的解决方案,我认为最好的解决方案是使用CodeRush或Resharper为我生成所有的后备店.

最佳答案
你不能这样做自动实现属性的规范很清楚:

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.

换句话说,他们只能“得到”和“set”,具有访问修饰符的可能性.

转载注明原文:自动实现的属性在C# - 代码日志