簡體   English   中英

有沒有辦法在c#中動態獲取方法名稱?

[英]Is there a way to get a method name dynamically in c#?

我有一個案例,我將方法名稱作為字符串傳遞給函數,但我不希望它硬編碼。 例如

void MyMethodName()
{
    // some code
}

void SomeOtherMethod()
{
    SomeExternalLibrary.ExternalClass.FunctionWithStringParameter("MyMethodName");
}

我想要這樣的東西:

FunctionWithStringParameter(MyMethodName.ToString());

這樣我可以通過“查找所有引用”來跟蹤方法調用,並且我可以毫無后顧之憂地使用重構。

也許最簡單的方法是提供一個重載FunctionWithStringParameter ,它可以將一個委托作為參數。

過載可能很簡單:

void FunctionWithStringParameter(Action d)
{
    FunctionWithStringParameter(d.Method.Name);
} 

並稱之為:

FunctionWithStringParameter(MyMethodName);

要接受具有不同簽名的方法,您必須提供許多不同的重載,或者接受Delegate作為參數,如下所示:

void FunctionWithStringParameter(Delegate d)
{
    FunctionWithStringParameter(d.Method.Name);
} 

不幸的是,如果你這樣做,你必須通過指定委托類型來調用它:

FunctionWithStringParameter((Action)MyMethodName);

這些天使用的一種技術是通過Expression

FunctionWithStringParameter(x => MyMethodName(x));

在你的方法中你可以選擇表達式來獲取方法名稱(並檢查它是一個簡單的方法調用表達式)。

請參閱從lambda表達式中檢索屬性名稱,以獲取有關如何分離lambda表達式的想法。

我不確定你要做什么,但是在引用方法和屬性時避免“魔術字符串”的一種方法是做ASP.NET MVC Helpers方法的做法,如下所示:

@Html.TextBoxFor(m=> m.SomeProperty)

並做一些允許你做的幫助:

string methodName = ReflectionHelper.MethodNameFor<TheTypeWIthTheMethod>(x=> x.TheMethod())

實現看起來像這樣:

static string MethodNameFor<T>(Expression<Action<T>> expression)
 {
        return ((MethodCallExpression)expression.Body).Method.Name;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM