Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

c# - Is it possible to implement Property Changed as Attribute?

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();
    }
}

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.

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;}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...