如何在C#中自动生成Decorator模式

前端之家收集整理的这篇文章主要介绍了如何在C#中自动生成Decorator模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些接口,以及一个实现此接口的类,说:
  1. interface IMyInterface
  2. {
  3. void Func1();
  4. void Func2();
  5. }
  6.  
  7. class Concrete : IMyInterface
  8. {
  9. public virtual void Func1() { //do something }
  10. public virtual void Func2() { //do something }
  11. }

现在,我想创建一个类,用一些特定的逻辑来装饰每个具体的类方法,在非生产环境中,在调用之前和之后执行.

  1. class Decorator : Concrete
  2. {
  3. public override void Func1() { Pre(); base.Func1; Post(); }
  4. public override void Func2() { Pre(); base.Func2; Post(); }
  5. }

我的问题是有一种更简单的方法自动生成这样的类,而不是在界面上使用反射并创建一个带有cs扩展名的文本文件

解决方法

就个人而言,我只需要明确记录需要的地方,但如果你设置使用装饰器这样做,你可以使用 RealProxy class.

它可能看起来像这样:

  1. public class DecoratorProxy<T> : RealProxy
  2. {
  3. private T m_instance;
  4.  
  5. public static T CreateDecorator<T>(T instance)
  6. {
  7. var proxy = new DecoratorProxy<T>(instance);
  8. (T)proxy.GetTransparentProxy();
  9. }
  10.  
  11. private DecoratorProxy(T instance) : base(typeof(T))
  12. {
  13. m_instance = instance;
  14.  
  15. }
  16. public override IMessage Invoke(IMessage msg)
  17. {
  18. IMethodCallMessage methodMessage = msg as IMethodCallMessage;
  19. if (methodMessage != null)
  20. {
  21. // log method information
  22.  
  23. //call method
  24. methodMessage.MethodBase.Invoke(m_instance,methodMessage.Args);
  25. return new ReturnMessage(retval,etc,etc);
  26.  
  27. }
  28.  
  29. }
  30. }

猜你在找的C#相关文章