如何查找执行函数的对象类型和名称

本文关键字:对象 类型 函数 执行 何查找 查找 | 更新日期: 2023-09-27 17:53:25

考虑以下代码:

class A
{
    public void Foo()
    {
        string thisFunction = // get the name of the executing function (Foo)
        string thisType = // get the name of the object type (A)
        Log.PrintLog(thisFunction, thisType);
    }
}
public static class Log
{
    public static void PrintLog(string function, string type)
    {
        Console.WriteLine("Call from function {0}, type {1}", function, type);
    }
}

如何找到执行函数的名称和对象类型?除了使用[CallerFilePath]和[CallerMemberName],还有其他解决方案吗?

如何查找执行函数的对象类型和名称

 string thisFunction = Reflection.MethodBase.GetCurrentMethod().Name; 
 string thisType = this.GetType().Name;

Int .Net4.5中有CallerMemberNameAttribute

方法的调用方的方法名或属性名方法。

你也可以试试:

new StackFrame(1).GetMethod().Name;

还检查这个有趣的链接回答:-你可以使用反射来找到当前执行的方法的名称吗?

通常你可以在任何你想要的地方创建StackTrace:

StackTrace st = new StackTrace();

然后它只是循环通过StackFrames:

StackFrame[] sf = st.GetFrames();
// in case your PrintLog has overloads or recursions
//  it may appear several times in the stack
string ownName = "PrintLog"; 
MethodInfo curMethod = null;
for(int i = 0; i < sf.Length; i++) {
     curMethod = sf[i].GetMethod();
     if(ownName != curMethod.Name)
         break;
}
Console.WriteLine("Call from function {0}, type {1}", 
                  curMethod.Name, 
                  curMethod.DeclaringType.Name);

您甚至可以标识类和参数(您可以使用MethodInfo对象)

我个人将Time TID调用者类+类型+名称放入我的日志上下文中。


据我所知,您想将函数名称和类型解析为PrintLog函数。那太乱了!

这种方法的美妙之处在于,您不必这样做。您可以在 PrintLog方法中检索调用者的名称和类型。

如果您可以接受路径而不是类型名称:

class A
{
    public void Foo()
    {
        Log.PrintLog();
    }
}
public static class Log
{
    public static void PrintLog([CallerMemberName] string function = null,
                                [CallerFilePath] string path = null)
    {
        Console.WriteLine("Call from function {0}, file {1}", function, path);
    }
}

对于实例方法,您可以选择使用GetType()来获取当前类型——但是这对于静态方法是不可能的。所以你可以使用:

public static void PrintLog(object obj = null,
       [CallerMemberName] string function = null,
       [CallerFilePath] string path = null)
{
    string name = obj == null ? path : obj.GetType().Name;
    Console.WriteLine("Call from function {0}, name {1}", function, name);
}

:

Log.PrintLog(this);

正如这里所解释的,您可以使用MethodInfo类来查找返回类型为MethodInfo.ReturnType