有这样一个需求。使用特性实现对特定的方法进行日志记录.如:[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方法录日志,否则直接执行方法。

解决方案 »

  1.   

    我现在能做到每个方法都进来再根据是否有My特性来写日志,我想更进一步,没有my特性就不用进来
      

  2.   


    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
      

  3.   


    仔细看了您的代码,并没有满足我的要求,我的要求是根据有无 SuppressContextLogAttribute 特性来限制进入Invoke 方法来达到记日志,而不是在Invoke中的来得到自定义特性来判断。而且,我不想采用装饰模式对方法里面的业务逻辑代码有任何影响。My my = MyLogWrapper.Wrap(new My());     我已经能不通过装饰模式在不影响任何业务代码的情况下记录日志,但仍然是根据特性标记来判断是否记录日志的。感谢回复。
      

  4.   

    参考 PostSharp 的 Document.