我想做这样的事情:
public MyFunction(int integerParameter, string stringParameter){
//Do this:
LogParameters();
//Instead of this:
//Log.Debug("integerParameter: " + integerParameter +
// ", stringParameter: " + stringParameter);
}
public LogParameters(){
//Look up 1 level in the call stack (if possible),
//Programmatically loop through the function's parameters/values
//and log them to a file (with the function name as well).
//If I can pass a MethodInfo instead of analyzing the call stack, great.
}
我什至不确定我想要做什么是可能的,但是如果能够在运行时自动将参数名称/值输出到文件而无需显式编写代码来记录它们,那就太好了。
是否可以?
我意识到人们链接到其他提到 PostSharp 的问题,但我忍不住发布解决我的问题的代码(使用 PostSharp),以便其他人可以从中受益。
class Program {
static void Main(string[] args) {
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
new MyClass().MyMethod(44, "asdf qwer 1234", 3.14f, true);
Console.ReadKey();
}
}
public class MyClass {
public MyClass() {
}
[Trace("Debug")]
public int MyMethod(int x, string someString, float anotherFloat, bool theBool) {
return x + 1;
}
}
[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) {
Trace.WriteLine(string.Format("Entering {0}.{1}.",
args.Method.DeclaringType.Name,
args.Method.Name), category);
for (int x = 0; x < args.Arguments.Count; x++) {
Trace.WriteLine(args.Method.GetParameters()[x].Name + " = " +
args.Arguments.GetArgument(x));
}
}
public override void OnExit(MethodExecutionArgs args) {
Trace.WriteLine("Return Value: " + args.ReturnValue);
Trace.WriteLine(string.Format("Leaving {0}.{1}.",
args.Method.DeclaringType.Name,
args.Method.Name), category);
}
}
只需添加Trace
方法的属性将导致输出非常好的调试信息,如下所示:
Debug: Entering MyClass.MyMethod.
x = 44
someString = asdf qwer 1234
anotherFloat = 3.14
theBool = True
Return Value: 45
Debug: Leaving MyClass.MyMethod.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)