如何自动生成C#Decorator模式 [英] How to auto generate Decorator pattern in C#

查看:135
本文介绍了如何自动生成C#Decorator模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些接口,实现此接口,一类说:

I have some interface, and a class implementing this interface, say:

interface IMyInterface
{
     void Func1();
     void Func2();
}

class Concrete : IMyInterface
{
     public virtual void Func1() { //do something }
     public virtual void Func2() { //do something }
}

现在,我想要创建装饰的每一个类具体的类方法与一些特定的逻辑,在非生产环境之前,呼叫后执行。

Now, I want to create a class that decorates each of the concrete class methods with some specific logic, to be executed in non production environment, before and after the call.

class Decorator : Concrete
{ 
     public override void Func1() { Pre(); base.Func1; Post(); }
     public virtual void Func2() { Pre(); base.Func2; Post(); }
}



我的问题是有没有汽车更简单的方式产生比使用其他类似的类在界面上的反射,并创建CS扩展名的文本文件?

My question is there a simpler way to auto generate such class other than use reflection on the interface and create a text file with cs extension?

推荐答案

个人而言,我只想明确记录在需要的地方,但如果你设置在使用装饰要做到这一点,你可以使用 RealProxy类< 。/ A>

Personally I would just explicitly log where needed, but if you are set on using a decorator to do this you could use the RealProxy class.

这可能是这个样子:

public class DecoratorProxy<T> : RealProxy
{
    private T m_instance;

    public static T CreateDecorator<T>(T instance)
    {
        var proxy = new DecoratorProxy<T>(instance);
        (T)proxy.GetTransparentProxy();
    }

    private DecoratorProxy(T instance) : base(typeof(T))
    {
        m_instance = instance;

    }
    public override IMessage Invoke(IMessage msg)
    {
        IMethodCallMessage methodMessage = msg as IMethodCallMessage;
        if (methodMessage != null)
        {
            // log method information

            //call method
            methodMessage.MethodBase.Invoke(m_instance, methodMessage.Args);
            return new ReturnMessage(retval, etc,etc);

        }

    }
}

这篇关于如何自动生成C#Decorator模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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