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

我找到了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) }); } 

所以我可以将Property更改为:

 private bool _foo; public bool Foo { get { _foo; } private set { _foo = value; this.OnPropertyChanged(); } } 

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

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

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

 [OnPropertyChanged] public bool Foo {set;get;} 

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

你需要某种AOP系统才能做到这一点。

你从你的类中包装或inheritance的东西,并在包装​​器/后代中动态生成必要的管道来处理这个,或者像Postsharp这样的系统在编译后重写你的代码。

.NET没有内置任何东西来处理这个问题。