是否可以将属性更改为属性?

Tho*_*ing 3 c# wpf inotifypropertychanged

我找到了一个Propperty Changed Event的实现,我可以在没有Web中属性名称的情况下更改Call Property.然后我在这里建立了一个扩展方法

public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged, string    propertyName = null)
{
    if (propertyName == null)
        propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_", "");
    FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
    if (field == (FieldInfo) null)
        return;
    object obj = field.GetValue((object) iNotifyPropertyChanged);
    if (obj == null)
        return;
    obj.GetType().GetMethod("Invoke").Invoke(obj, new object[2]
    {
        (object) iNotifyPropertyChanged,
        (object) new PropertyChangedEventArgs(propertyName)
    });
}
Run Code Online (Sandbox Code Playgroud)

所以我可以将Property更改为:

private bool _foo;
public bool Foo
{
    get { _foo; }
    private set
    {
        _foo = value;
        this.OnPropertyChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

但我想,如果我在使用Property更改时不必实现属性的getter和setter,那就更好了.

现在有人如何将OnPropertyChanged方法作为属性实现,也许是用AOP?

因此,Auto-Property可用于Property Changed,如下所示:

[OnPropertyChanged]
public bool Foo {set;get;}
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 8

查看FodyPropertyChanged加载项.它将在编译后修改IL,以添加代码以引发PropertyChanged属性的事件.它类似于在Lasse的回答中提到的PostSharp,但它是免费的和开源的.