问题描述
我找到了财产变更事件"的实现,可以在其中调用财产变更而无需网络中财产名称的情况.然后我在这里建立了一个扩展方法
I have found an implementation of Propperty Changed Event, where i can Call Property changed without the Name of the Property in the web. And then i have build a Extension Method with it wich is here
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)
});
}
这样我就可以调用属性更改,如下所示:
So i can call Property changed like this:
private bool _foo;
public bool Foo
{
get { _foo; }
private set
{
_foo = value;
this.OnPropertyChanged();
}
}
但是我想,如果我在使用Property更改时不必实现Property的getter和setter方法,那就更好了.
But I thought, it would be nicer if i don't have to implement the getter and setter of a Property when i use Property changed.
现在有人可以通过AOP将OnPropertyChanged方法实现为属性吗?
Does anyone now how to implement the OnPropertyChanged Method as Attribute, maybe with AOP?
这样,就可以将自动属性用于属性更改,例如:
So that Auto-Property can be used for Property Changed like this:
[OnPropertyChanged]
public bool Foo {set;get;}
推荐答案
查看 Fody ,然后 PropertyChanged 加载项.编译后它将修改IL,以添加代码以引发属性的PropertyChanged
事件.它类似于Lasse的回答中提到的PostSharp,但它是免费的开放源代码.
Check out Fody, and the PropertyChanged add-in. It will modify the IL after compilation to add the code to raise the PropertyChanged
event for your properties. It's similar to PostSharp, mentioned in Lasse's answer, but it's free and open-source.
这篇关于是否可以实现将属性更改为属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!