A method that is executed at any time when access to a class (get or set) refers to it?

C # -.net 3.5

I have a family of classes that inherit from the same base class. I want the method in the base class to be called at any time when the resource in the derrive class is accessed (get or set). However, I do not want to write code in each property to call the base class ... instead, I hope that there is a declarative way to "sink" this activity into the base class.

Adding some requirements to the requirement, I need to determine the name of the available property, the value of the property, and its type.

I believe that a solution would be a clever combination of delegate, generics and reflection. I can imagine creating some type of arrays of delegate assignments at runtime, but repeating over MemberInfo in the constructor would affect performance more than I would like. Again, I hope that there is a more direct "declarative" way to do this.

Any ideas are most appreciated!

+5
source share
2 answers

, 95% . - . PostSharp, OnFieldAccessAspect. :

[Serializable]
public class FieldLogger : OnFieldAccessAspect {
    public override void OnGetValue(FieldAccessEventArgs eventArgs) {
        Console.WriteLine(eventArgs.InstanceTag);
        Console.WriteLine("got value!");
        base.OnGetValue(eventArgs);
    }

    public override void OnSetValue(FieldAccessEventArgs eventArgs) {
        int i = (int?)eventArgs.InstanceTag ?? 0;
        eventArgs.InstanceTag = i + 1;
        Console.WriteLine("value set!");
        base.OnSetValue(eventArgs);
    }

    public override InstanceTagRequest GetInstanceTagRequest() {
        return new InstanceTagRequest("logger", new Guid("4f8a4963-82bf-4d32-8775-42cc3cd119bd"), false);
    }
}

, FieldLogger, . Presto!

+4

, , , . INotifyPropertyChanged . - :

public class A : INotifyPropertyChanged
{

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected virtual void RaiseOnPropertyChanged(object sender, string propertyName)
    {
        if (this.PropertyChanged != null)
            PropertyChanged(sender, new PropertyChangedEventArgs(propertyName);
    }

    public A()
    {
        this.PropertyChanged += new PropertyChangedEventHandler(A_PropertyChanged);
    }

    void A_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        //centralised code here that deals with the changed property
    }
}


public class B : A
{
    public string MyProperty
    {
        get { return _myProperty; }
        set 
        {
            _myProperty = value;
            RaiseOnPropertyChanged(this, "MyProperty");
        }
    }

    public string _myProperty = null;
}
+2