我有一些接口,以及一个实现此接口的类,说:
interface IMyInterface
{
void Func1();
void Func2();
}
class Concrete : IMyInterface
{
public virtual void Func1() { //do something }
public virtual void Func2() { //do something }
}
现在,我想创建一个类,用一些特定的逻辑来装饰每个具体的类方法,在非生产环境中,在调用之前和之后执行.
class Decorator : Concrete
{
public override void Func1() { Pre(); base.Func1; Post(); }
public override void Func2() { Pre(); base.Func2; Post(); }
}
我的问题是有一种更简单的方法来自动生成这样的类,而不是在界面上使用反射并创建一个带有cs扩展名的文本文件?
解决方法
就个人而言,我只需要明确记录需要的地方,但如果你设置使用装饰器这样做,你可以使用
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);
}
}
}