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

时间:2011-03-22 05:07:29

标签: c#

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

6 个答案:

答案 0 :(得分:173)

当前班级名称:

this.GetType().Name;

当前方法名称:

using System.Reflection;

// ...

MethodBase.GetCurrentMethod().Name;

由于您将此用于记录目的,因此您可能也有兴趣获取current stack trace

答案 1 :(得分:11)

答案 2 :(得分:8)

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

答案 3 :(得分:6)

我将上面的例子稍微改成了这段工作示例代码:

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
        }
    }
}

输出:

Program.FooBar enter
Program.FooBar leave

答案 4 :(得分:4)

是的! 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;
    }
}    
}

此代码的输出将为:

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

希望我帮助过你!

JAL

答案 5 :(得分:1)

您可以获取当前的类名,但无论如何我都无法想到获取当前的方法名称。但是,可以获得电流方法的名称。

string className = this.GetType().FullName;
System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
foreach (var method in methods)
    Console.WriteLine(method.Name);
相关问题