111,129
社区成员
发帖
与我相关
我的任务
分享
public class test
{
public void start()
{
Console.WriteLine("开始");
}
public void stop()
{
Console.WriteLine("结束");
}
public void show1()
{
start();
//其他实现
stop();
}
public void show2(string str)
{
start();
//其他实现
stop();
}
public void show3(int num,string str)
{
start();
//其他实现
stop();
}
//…
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
My my = MyLogWrapper.Wrap(new My()); //<----
MessageBox.Show(my.Test1() + " " + my.Test2 + " " + my.Test3());
}
}
class My : Component
{
public string Test1() { return "hello"; }
public string Test2 { get { return "world"; } }
[MyLogWrapper.SuppressContextLogAttribute] //<----
public string Test3() { return "what?"; }
}
public class MyLogWrapper
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property )]
public class SuppressContextLogAttribute : Attribute
{
}
public static T Wrap<T>(T target) where T : MarshalByRefObject
{
return new MyProxy(typeof(T), target).GetTransparentProxy() as T;
}
private class MyProxy : RealProxy
{
public MyProxy(Type t, MarshalByRefObject target) : base(t)
{
this.target = target;
}
public override IMessage Invoke(IMessage msg)
{
MethodBase method = (msg as IMethodMessage).MethodBase;
bool logging = method.GetCustomAttributes(typeof(SuppressContextLogAttribute), false).Length == 0;
if (logging) System.Diagnostics.Trace.WriteLine("Start " + method.Name);
IMessage result = RemotingServices.ExecuteMessage(target, msg as IMethodCallMessage);
if (logging) System.Diagnostics.Trace.WriteLine("Stop " + method.Name);
return result;
}
private MarshalByRefObject target;
}
}
private void ShowEx<T>(Action<T> showAction, T showParam)
{
Start();
if (showAction != null)
{
showAction(showParam);
}
Stop();
}