在运行时替换Property Setter方法

Ian*_*ton 5 c# reflection

我有许多共享基本类的对象,我希望拦截所有设置属性值的调用,并记录是否已基于每个实例设置.

我可以在运行时用Reflection替换属性的Set方法吗?

Mar*_*ell 6

一种方法是使属性成为虚拟,并在运行时通过reflection-emit创建一个子类,覆盖属性,添加代码.但是,这是先进的,并且需要您始终确保创建子类(因此代码中没有"新").

然而; 我想知道是否只是简单地实现INotifyPropertyChanged并处理事件更简单.另一种选择是首先将处理构建到常规类中.有一些方法可以减少重复次数,特别是如果你有一个可以添加的公共基类

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

private int foo;
public int Foo {
    get { return foo; }
    set { SetField(ref foo, value); }
}
Run Code Online (Sandbox Code Playgroud)