How to inject method to auto property in .Net Framework

前端 未结 3 1467
夕颜
夕颜 2021-01-15 15:15

I have some class Foo with many properties:

public class Foo
{
    public int Property1 { get; set; }

    public int Property2 { get; set; }

    public int         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-15 15:55

    I don't think there is a way to do that at runtime with reflection. What you would probably want to do is use an AOP (aspect-oriented) approach, but that too isn't really supported by the .NET framework. You could use PostSharp to do it, if you don't mind using a compiler extension, or look into using Unity2 to do AOP.

    Edit: You could also consider Castle DynamicProxy. Or, if you have a firm grasp of DynamicMethods and IL code, you could make your own proxy generator class.

    However, I think in most cases, you will have to code the rest of your application appropriately to handle the proxies. In other words, instead of doing:

    Foo f = new Foo();
    f.Property1 = 123;
    

    You would have to do something like:

    Foo f = Generator.GetProxy(); // this code is fake. just indicates that you need to get an instance of Foo from a proxy generator, be it DynamicProxy or Unity or whatever.
    f.Property1 = 123;
    

提交回复
热议问题