是否有一个返回当前类/方法名称的函数?

Cra*_*ton 90 c#

在C#中,是否有一个返回当前类/方法名称的函数?

Cam*_*ron 174

当前班级名称:

this.GetType().Name;
Run Code Online (Sandbox Code Playgroud)

当前方法名称:

using System.Reflection;

// ...

MethodBase.GetCurrentMethod().Name;
Run Code Online (Sandbox Code Playgroud)

由于您将此用于记录目的,您可能还有兴趣获取当前堆栈跟踪.

  • 非静态方法的当前类名:`this.GetType().Name;`静态方法的当前类名:`System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;` (32认同)
  • 使用反射的成本很高,而且有时是不必要的。这个问题通常源于对硬编码名称的厌恶——尽管实际上知道它。但是您可以通过使用 nameof(<MethodNameHere>) 代替字符串来让编译器处理它。确实,它并不能避免复制/粘贴错误,其中方法引用最终有效,但它的速度使其非常有用。 (2认同)

小智 9

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
Run Code Online (Sandbox Code Playgroud)


Jan*_*ans 7

我将上面的示例稍微更改为这段工作示例代码:

public class MethodLogger : IDisposable
{
    public MethodLogger(MethodBase methodBase)
    {
        m_methodName = methodBase.DeclaringType.Name + "." + methodBase.Name;
        Console.WriteLine("{0} enter", m_methodName);
    }

    public void Dispose()
    {
        Console.WriteLine("{0} leave", m_methodName);
    }
    private string m_methodName;
}

class Program
{
    void FooBar()
    {
        using (new MethodLogger(MethodBase.GetCurrentMethod()))
        {
            // Write your stuff here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Program.FooBar enter
Program.FooBar leave
Run Code Online (Sandbox Code Playgroud)


小智 5

是的!MethodBase 类的静态 GetCurrentMethod 将检查调用代码以查看它是构造函数还是普通方法,并返回 MethodInfo 或 ConstructorInfo。

此命名空间是反射 API 的一部分,因此您基本上可以通过使用它来发现运行时可以看到的所有内容。

您将在此处找到 API 的详尽说明:

http://msdn.microsoft.com/en-us/library/system.reflection.aspx

如果你不想浏览整个图书馆,这里是我制作的一个例子:

namespace Canvas
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        DiscreteMathOperations viola = new DiscreteMathOperations();
        int resultOfSummation = 0;
        resultOfSummation = viola.ConsecutiveIntegerSummation(1, 100);
        Console.WriteLine(resultOfSummation);
    }
}

public class DiscreteMathOperations
{
    public int ConsecutiveIntegerSummation(int startingNumber, int endingNumber)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        int result = 0;
        result = (startingNumber * (endingNumber + 1)) / 2;
        return result;
    }
}    
}
Run Code Online (Sandbox Code Playgroud)

此代码的输出将是:

Void Main<System.String[]> // Call to GetCurrentMethod() from Main.
Int32 ConsecutiveIntegerSummation<Int32, Int32> //Call from summation method.
50 // Result of summation.
Run Code Online (Sandbox Code Playgroud)

希望我能帮到你!

日航