开发者

How to use reflection inside a static method

开发者 https://www.devze.com 2023-01-27 19:44 出处:网络
Ive got a logging method: public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)

Ive got a logging method:

    public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)
    {

        StreamWriter writer;

        //Environment.ExpandEnvironmentVariables("%SystemDrive%") [will get to the c drive]
        if (EnumsAndConstants.EnableApplicationLogging)
        {
            writer = new StreamWriter(logFilePathArg, true);
            writer.Write("Time: " + DateTime.Now.ToString() + " Message: " + messageArg);
            writer.Write(Environment.NewLine);
            writer.Flush();
            writer.Close();
        }

    }

And I am trying to access this.GetType().Name inside it but im not allowed to. Is there anyway around this? I want to easily ge开发者_如何转开发t the calling class name when this method is called without having to rewrite all calls to this method...


As it's static there is no this instance. You'd usually pass the actual instance into to method to provide method data. I have a logging class which accepts a Reflection.MethodInfo instance to output. As you don't want to change the method signature, perhaps you'd have better luck using the StackTrace diagnostics class:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace%28VS.71%29.aspx

Get the previous Frame, then recover the calling method. The example pretty much says it all.


You can use stackTrace.GetFrame(1).GetMethod() to retrieve the calling method and from there the associated class name

0

精彩评论

暂无评论...
验证码 换一张
取 消