如何在C#中将类或方法名称识别为方法?

时间:2015-09-16 10:11:47

标签: c# class methods

我不知道是否可能,但如果有办法做到这一点,请建议。 我有一个方法,我用不同的类调用这个方法,所以我怎么能够 知道(类名)到方法,从哪个方法调用?

以下是我的情景,

public class Employee()
{
    protected bool Check()
    {
         //Here how will I know method name(Test1 or Test2) from which call is made? Please note I can't use any parameter with Check method.
    }
    public void Test1()
    {
         Check();
    }
    public void Test2()
    {
         Check();
    }
}

4 个答案:

答案 0 :(得分:2)

你可以试试这个:

project Properties -> Linker -> Input -> Additional Dependencies

在C#6.0中,您可以使用nameof

string myClass = MethodBase.GetCurrentMethod().DeclaringType.Name;

答案 1 :(得分:0)

您可以使用

var className = this.GetType().Name;

答案 2 :(得分:0)

您可以使用StackTrace;

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name);

感谢Jason

答案 3 :(得分:-1)

你会找到答案 here

using System.Diagnostics;

// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);