luc*_*mia 5 c# debugging attributes stack-trace
在Python中,我可以使用装饰器来跟踪函数调用,它的变量和返回值.这是非常容易使用.我只是想知道C#可以做同样的事情吗?
我发现在线有一个CallTracing属性的示例代码.但是,它没有显示我预期的结果.
C#属性是否与python的装饰器具有相似的概念?
谢谢你和最诚挚的问候!
[AttributeUsage(AttributeTargets.Method | AttributeTargets.ReturnValue |
AttributeTargets.Property, AllowMultiple = false)]
public class CallTracingAttribute : Attribute
{
public CallTracingAttribute()
{
try
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
Trace.TraceInformation("{0}->{1} {2}:{3}",
stackFrame.GetMethod().ReflectedType.Name,
stackFrame.GetMethod().Name,
stackFrame.GetFileName(),
stackFrame.GetFileLineNumber());
Debug.WriteLine(string.Format("{0}->{1} {2}:{3}",
stackFrame.GetMethod().ReflectedType.Name,
stackFrame.GetMethod().Name,
stackFrame.GetFileName(),
stackFrame.GetFileLineNumber()));
}
catch
{
}
}
}
class Program
{
[CallTracing]
static int Test(int a)
{
return 0;
}
[CallTracing]
static void Main(string[] args)
{
Test(1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您愿意通过某些约束(即,从ContextBoundObject派生,除其他外),.NET确实支持调用拦截体系结构.您可以在MSDN杂志artcile中找到有关如何执行此操作的完整说明,该杂志标题为"通过将自定义服务注入对象的拦截链来解耦组件".
此外,您可能需要考虑将类抽象为接口,然后通过接口实现转发它们来拦截调用.
最后,看看WCF.它有一个非常明确的拦截体系结构(不要让它的Web服务欺骗你,你可以简单地创建自己的通道传输,这是一个空通道),你可以利用它来完成你想要的.