簡體   English   中英

如何在C#中將類或方法名稱標識為方法?

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

我不知道是否可能,但是如果有某種方法可以做到這一點,請提出建議。 我有一個方法,並且用不同的類來調用此方法,那么如何知道方法的名稱(類名)呢?

以下是我的情況,

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

您可以嘗試以下方法:

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

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

nameof(YourMethodname)

你可以用

var className = this.GetType().Name;

您可以使用StackTrace ;

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

感謝傑森

您將在這里找到答案

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