有这样一个需求。使用特性实现对特定的方法进行日志记录.如:[MyAttribute(User="hwj383",Operate="DeleteUser",DateTime="xxxxx")]
public void Method()
{
//方法逻辑
}记日志的方法
public void Log()
{
object[] obj = MethodInfo.GetCustomerAttribute(typeof(MyAttribute),false))
if(obj.length != 0)
{
MyAttribute my = obj[0] as MyAttribute
my.User
}
}现在要达到的要求是:
只要方法上有My特性就在进入方法前先执行Log方法录日志,否则直接执行方法。
public void Method()
{
//方法逻辑
}记日志的方法
public void Log()
{
object[] obj = MethodInfo.GetCustomerAttribute(typeof(MyAttribute),false))
if(obj.length != 0)
{
MyAttribute my = obj[0] as MyAttribute
my.User
}
}现在要达到的要求是:
只要方法上有My特性就在进入方法前先执行Log方法录日志,否则直接执行方法。
解决方案 »
- 各位,请教一下,我想做个数据库统计的程序,放到服务器上,让每个人都能使用.有什么比较安全的方法没?这涉及到网络编程了吧?
- WinForm的dateTimePicker如何精确到毫秒
- 修改了c#的 dataset的fill调用的sql,如何修改Update?
- 小弟现在在做一个.NET的KTV项目有一些功能还不会实现,哪位大哥帮帮忙,谢谢了!!
- 在C#中如何调用系统中以有的文件
- 如何根据权限跳转页面?
- 如何得到线程的类名 。在线等
- 我要疯了!上海招SQL SERVRE DBA的太少了!谁介绍工作我给现金!至少500!你定个价!
- C#中如何做结构转换?
- 当关闭一个子窗口时父窗口会闪一下,怎么办?
- 高分请教:调试环境和部署环境下,多线程判断结束的问题!
- 寻找C#高手帮我看看socket通信问题,搞了一天了。。
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;
}
}原文发在http://topic.csdn.net/u/20101018/21/96cd7007-6b49-4595-b0dd-dbf29b63216d.html
仔细看了您的代码,并没有满足我的要求,我的要求是根据有无 SuppressContextLogAttribute 特性来限制进入Invoke 方法来达到记日志,而不是在Invoke中的来得到自定义特性来判断。而且,我不想采用装饰模式对方法里面的业务逻辑代码有任何影响。My my = MyLogWrapper.Wrap(new My()); 我已经能不通过装饰模式在不影响任何业务代码的情况下记录日志,但仍然是根据特性标记来判断是否记录日志的。感谢回复。