简体   繁体   English

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

[英]How to identfiy Class or Method Name into method in C#?

I don't know it is possible or not, but if there is some way to do this then please suggest. 我不知道是否可能,但是如果有某种方法可以做到这一点,请提出建议。 I have one method and I am call this method with different classes, so how will I able to know(Class Name) into method, that from which method is called? 我有一个方法,并且用不同的类来调用此方法,那么如何知道方法的名称(类名)呢?

Below is my scenario, 以下是我的情况,

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

You can try this: 您可以尝试以下方法:

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

And in C# 6.0 then you can use nameof 在C#6.0中,您可以使用nameof

nameof(YourMethodname)

你可以用

var className = this.GetType().Name;

You can use the StackTrace ; 您可以使用StackTrace ;

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

Thanks to Jason 感谢杰森

You will find your answer here 您将在这里找到答案

using System.Diagnostics;

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM