【问题标题】:Dynamic parameters in postsharppostsharp中的动态参数
【发布时间】:2016-08-31 14:37:27
【问题描述】:

我正在尝试使用 post sharp 动态分配属性。例如在下面的示例中,我想要自定义日志消息。但问题是我如何在属性部分设置xname。在第一个日志中,我希望日志消息的开头有人员姓名,但第二个日志消息的末尾有人员姓名。


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationLogging
{
    internal static class Program
    {
        private static void Main()
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
            SayHelloInTurkish("Ayse");
            SayGoodByeSayHelloInEnglish("Elizabeth");
        }
        [Trace("xname Loglanıyor Gunaydın")]
        private static void SayHelloInTurkish(string personName)
        {
            Console.WriteLine("Hello, world.");
        }
        [Trace("Good Bye Logging for xname")]
        private static void SayGoodByeSayHelloInEnglish(string personName)
        {
            Console.WriteLine("Good bye, world.");
        }
    } 
}

using System;
using System.Diagnostics;
using PostSharp.Aspects; 

namespace ConsoleApplicationLogging
{
    [Serializable]
    public sealed class TraceAttribute : OnMethodBoundaryAspect 
    {
        private readonly string category;

        public TraceAttribute(string category)
        {
            this.category = category;
        }

        public string Category { get { return category; } }

        public override void OnEntry(MethodExecutionArgs args)
        {
            if (args.Method.DeclaringType != null)
            Trace.WriteLine(string.Format("Entering {0}.{1}.",
                args.Method.DeclaringType.Name, args.Method.Name), this.category);
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            if (args.Method.DeclaringType != null)
            Trace.WriteLine(string.Format("Leaving {0}.{1}.",
                args.Method.DeclaringType.Name, args.Method.Name), this.category);
        }
    } 
}

【问题讨论】:

    标签: c# postsharp aop


    【解决方案1】:

    如果我理解正确,您需要这样的东西(不包括完整性检查):

    this.category.Replace("xname", (string)args.Arguments[0])
    

    如果我没有正确理解,请随时在下面发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      相关资源
      最近更新 更多