一个方法可以执行任何时候访问一个类属性

一个方法可以执行任何时候访问一个类属性

本文介绍了一个方法可以执行任何时候访问一个类属性(获取或设置)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# - .net 3.5

C# - .net 3.5

我有一系列继承自同一基类的类。
我希望在访问(获取或设置)被访问的类中的属性时,在基类中调用一个方法。但是,我不想在每个属性中编写代码来调用基类...而是,我希望有一个声明性的方法来将此活动沉入到基类中。

I have a family of classes that inherit from the same base class.I want a method in the base class to be invoked any time a property in a derrived class is accessed (get or set). However, I don't want to write code in each and every property to call the base class... instead, I am hoping there is a declarative way to "sink" this activity into the base class.

添加一些香料的要求,我确实需要确定被访问的属性的名称,属性值及其类型。

Adding some spice to the requirement, I do need to determine the name of the property that was accessed, the property value and its type.

我想象,解决方案将是代表,泛型和反思的巧妙组合。我可以设想在运行时创建一些类型的委托分配数组,但是在构造函数中遍历成员信息会影响性能,而不是我想要的。再次,我希望有一个更直接的声明性的方式来做到这一点。

I imagine the solution would be a clever combination of a delegate, generics, and reflection. I can envision creating some type of array of delegate assignments at runtime, but iterating over the MemberInfo in the constructor would impact performance more than I'd like. Again, I'm hoping there is a more direct "declarative" way to do this.

任何想法都非常感谢!

推荐答案

你不能自动执行,但是几乎可以免费得到95%的。这是面向方面编程的典型案例。查看,其中有类。以下是您如何解决您的问题:

You can't do it automatically, but you can pretty much get 95% for free. This is a classic case for aspect-oriented programming. Check out PostSharp, which has the OnFieldAccessAspect class. Here's how you might solve your problem:

[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!

Now, anything that inherits from FieldLogger will get the same behavior. Presto!

这篇关于一个方法可以执行任何时候访问一个类属性(获取或设置)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:45