Use C# attribute to track function call, variables, and return value?

拜拜、爱过 提交于 2020-01-01 05:31:05

问题


In Python, I can use decorators to trace the function call, its variables and return values. It is very easy to use. I just wonder can C# do the same thing?

I find out there is a sample code of CallTracing Attribute online. However, it didn't show the result I expected.

Does C# attributes have similar concepts as python's decorator?

Thanks you and Best Regards!

[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);
    }
}

回答1:


.NET does support a call-interception architecture, if you are willing to live by some constraints (namely, deriving from ContextBoundObject, among other things). You can find a full description of how to do this in the MSDN magazine artcile titled "Decouple Components by Injecting Custom Services into Your Object's Interception Chain".

Also, you might want to consider abstracting out your classes into interfaces and then intercepting the calls by forwarding them through your interface implementations.

Finally, take a look at WCF. It has a very well-defined interception architecture (don't let the fact that it's web services fool you, you can simply create your own channel transport which is a null channel) which you can leverage to do exactly what you want.




回答2:


C# doesn't support AOP out of the box. You need an IL rewriter like PostSharp for that.




回答3:


You can track all .NET function calls, parameters and return values without manually adding decorators using the Runtime Flow tool (developed by me).



来源:https://stackoverflow.com/questions/3981440/use-c-sharp-attribute-to-track-function-call-variables-and-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!