在运行时更换物业setter方法 [英] Replace Property Setter method at runtime

查看:91
本文介绍了在运行时更换物业setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,都有一个共同的基类,我想拦截,如果这些都已经在每个实例的基础上设置了设置属性值并记录所有通话的对象。

I have a number of objects that all share a common base class, I wish to intercept all calls that set Property values and record if these have been set on a per instance basis.

我可以替代属性的设置方法在具有反射运行?

Can I replace the Set Method of a Property at runtime with Reflection?

推荐答案

一种方法存在使物业虚拟的,并在运行时通过创建一个子类反射发出的覆盖性能,加入你的代码。然而,这是先进的,并要求你始终确保创建子类(所以没有在代码中的新)

One approach there is to make the property virtual, and at runtime create a subclass via reflection-emit that override the properties, adding your code. However, this is advanced, and requires you always make sure to create the subclass (so no "new" in code).

不过,我不知道如果简单地实施INotifyPropertyChanged的和处理该事件是简单。另一种选择是刚刚建立的处理成为摆在首位普通班。有使这个少重复的某些方面,特别是如果你有一个共同的基类,你可以添加一个

However; I wonder if simply implementing INotifyPropertyChanged and handling the event is simpler. The other option is to just build the handling into the regular class in the first place. There are some ways of making this less repetitive, especially if you have a common base-class where you could add a

protected void SetField<T>(ref T field, T value)
{
    if(!EqualityComparer<T>.Default.Equals(field,value))
    {
        field = value;
        // extra code here
    }
}

通过

private int foo;
public int Foo {
    get { return foo; }
    set { SetField(ref foo, value); }
}

这篇关于在运行时更换物业setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆