如何在静态方法中使用反射

时间:2010-11-30 11:39:56

标签: reflection static c#-4.0

我有一个记录方法:

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

    }

我正在尝试访问this.GetType()。在其中的名称,但我不允许。有没有办法解决?我希望在调用此方法时轻松获取调用类名称,而不必重写对此方法的所有调用...

2 个答案:

答案 0 :(得分:0)

因为它是静态的,所以没有this个实例。您通常会将实际实例传递给方法以提供方法数据。我有一个日志类,它接受一个Reflection.MethodInfo实例输出。由于您不想更改方法签名,也许您可​​以使用StackTrace诊断类获得更好的运气:

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

获取上一帧,然后恢复调用方法。这个例子几乎说明了一切。

答案 1 :(得分:0)

您可以使用stackTrace.GetFrame(1).GetMethod()来检索调用方法,并从那里检索关联的类名