问题描述
我有一些接口,一个实现这个界面的类,说:
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?
推荐答案
个人我只是明确记录需要的地方,但如果你设置使用装饰器来执行此操作,您可以使用。
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模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!