我正在尝试使用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);
}
}
}
答案 0 :(得分:0)
如果我理解正确,你需要这样的东西(不包括健全性检查):
this.category.Replace("xname", (string)args.Arguments[0])
如果我不理解,请随时在下面发表评论。