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

Reflection 如何在静态方法中使用反射,reflection,static,c#-4.0,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 (EnumsAndCons

我有一个记录方法:

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

    }

我正在尝试访问其中的.GetType().Name,但不允许访问。这有什么关系吗?我想在调用此方法时轻松获取调用类名,而不必重写对此方法的所有调用…

因为它是静态的,所以没有
实例。您通常会将实际实例传递到方法,以提供方法数据。我有一个日志类,它接受要输出的
Reflection.MethodInfo
实例。由于您不想更改方法签名,使用StackTrace diagnostics类可能会更好:


获取前一帧,然后恢复调用方法。这个例子很好地说明了这一切。

您可以使用
stackTrace.GetFrame(1).GetMethod()
检索调用方法,并从中检索关联的类名您到底想要什么类型?您可以执行
typeof(DeclaringClass)
/
MethodBase.GetCurrentMethod().DeclaringType
,但这只能提供记录器类的类型。如果需要调用此方法的类的类型,可以检查调用堆栈,但这充满了问题(可能是JIT内联等)。