简体   繁体   English

有没有办法在c#中动态获取方法名称?

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

I have a case where I pass a method name to a function as a string, but I don't want it hard-coded. 我有一个案例,我将方法名称作为字符串传递给函数,但我不希望它硬编码。 for example 例如

void MyMethodName()
{
    // some code
}

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

I want something like this: 我想要这样的东西:

FunctionWithStringParameter(MyMethodName.ToString());

THis way I can keep track of method calls by "Find All References", and I can use refactoring without worries. 这样我可以通过“查找所有引用”来跟踪方法调用,并且我可以毫无后顾之忧地使用重构。

Perhaps the easiest way would be to provide an overload FunctionWithStringParameter which can take a delegate as a parameter. 也许最简单的方法是提供一个重载FunctionWithStringParameter ,它可以将一个委托作为参数。

The overload could be as simple as: 过载可能很简单:

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

And call it like this: 并称之为:

FunctionWithStringParameter(MyMethodName);

To accept methods with different signatures, you'd have to either provide many different overloads, or accept Delegate as a parameter, like this: 要接受具有不同签名的方法,您必须提供许多不同的重载,或者接受Delegate作为参数,如下所示:

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

Unfortunately, if you do this, you would have to call it by specifying a delegate type: 不幸的是,如果你这样做,你必须通过指定委托类型来调用它:

FunctionWithStringParameter((Action)MyMethodName);

One technique used a lot these days is to pass an Expression . 这些天使用的一种技术是通过Expression

FunctionWithStringParameter(x => MyMethodName(x));

Inside your method you can pick the expression apart to get the method name being called (and check that it is a simple method call expression). 在你的方法中你可以选择表达式来获取方法名称(并检查它是一个简单的方法调用表达式)。

See Retrieving Property name from lambda expression for ideas on how to pick apart the lambda expression. 请参阅从lambda表达式中检索属性名称,以获取有关如何分离lambda表达式的想法。

I'm not sure what you are trying to do, but one way to avoid "magic strings" when referencing methods and properties is do do what the ASP.NET MVC Helpers methods do that look like this : 我不确定你要做什么,但是在引用方法和属性时避免“魔术字符串”的一种方法是做ASP.NET MVC Helpers方法的做法,如下所示:

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

and do some kind of helper that allows you to do : 并做一些允许你做的帮助:

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

The implementation would look something like that : 实现看起来像这样:

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