Is it possible to implement a property changed as an attribute?

I found an implementation of an event modified with Propperty where I can change a call property without a property name on the net. And then I have an extension method with it which 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 the property changed like this:

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

      

But I thought it would be better if I don't have to implement the getter and setter of the property when I use Property changed.

Does anyone now have how to implement the OnPropertyChanged method as an attribute, possibly with AOP?

So that Auto Property can be used for Changed property like this:

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

      

+3


source to share


2 answers


Check Fody and PropertyChanged is an add-on. It will change the IL after compilation to add code to raise an event PropertyChanged

for your properties. It's similar to PostSharp mentioned in Lasse's answer, but it's free and open source.



+7


source


You will need some sort of AOP system for this.

Either something where you wrap or inherit from your class and dynamically generate the necessary plumbing in the wrapper / descendant to handle this, or some system like Postsharp that rewrites your code after compilation.



There is nothing in .NET to handle this.

+4


source







All Articles