在C#中动态获取方法名最简单、最便宜的方法是什么?
我想将mathod名称放入字符串中,但我也不想使用硬编码值。相反,我希望通过反射动态地获取名称。我使用了以下,工作语句:在C#中动态获取方法名最简单、最便宜的方法是什么?,c#,reflection,.net-4.5,C#,Reflection,.net 4.5,我想将mathod名称放入字符串中,但我也不想使用硬编码值。相反,我希望通过反射动态地获取名称。我使用了以下,工作语句: "The method is called " + new Action(MyMethod).Method.Name; 我认为创建操作委托在语义上是不合适的。它表明将有一个方法调用,但相反,将有一个反射。我正在为类寻找类似于typeof操作符或GetType的东西,但在方法级别 模式Delegate.Method.Name是否是实现我目标的最佳标准方法 我的意思是不是当前
"The method is called " + new Action(MyMethod).Method.Name;
我认为创建操作
委托在语义上是不合适的。它表明将有一个方法调用,但相反,将有一个反射。我正在为类寻找类似于typeof操作符或GetType的东西,但在方法级别
模式Delegate.Method.Name
是否是实现我目标的最佳标准方法
我的意思是不是当前方法。应该给你当前方法的名称
"The method is called " + MethodInfo.GetCurrentMethod().Name;
使用MethodBase.GetCurrentMethod()这里是第一种方法
public static class MethodInfo
{
public static System.Reflection.MethodInfo From(Func<string, int> func)
{
return func.Method;
}
// Other members for Action<T>, Action<T1, T2> etc.
// Other members for Func<T>, Func<T1, T2> etc.
}
"The method is called " + new Func<string, int>(MyClass.MyMethod).Method.Name
“方法名为”+newfunc(MyClass.MyMethod).method.Name
目前最好的解决方案是:
ReflectionExtensionMethods
:
public static class ReflectionExtensionMethods
Action
、Action
等、Func
、Func
等添加多个方法。以下是操作的示例:
public static string GetMethodName(this Type @this, Expression<Action> expression)
{
return GetMethodNameInternal(@this, expression);
}
var owner = new Foo();
var methodName = typeof(Foo).GetMethodName(() => owner.VoidMethod());
var methodName = typeof(Foo).GetMethodName(() => Foo.StaticVoidMethod());
ReflectionExtensionMethods
可以通过返回属性和其他成员名称的方法进一步补充。我已经编辑了我的问题。实际上,该方法不是当前的方法。谢谢你的回答。如果不是当前方法,那么是哪种方法?当前类的任何方法。例如,该类有两个方法A和B。我在方法A中,希望动态获取B的名称。B的名称将来可能会更改为C。如果我写了“B”,那么我的编译器不会警告我仍然使用“B”而不是最新的“C”的不一致消息。您如何考虑指定哪种方法。你的问题与此类似,你的名字不详没有人会告诉我你的名字,但我想知道你的名字。不可能如果我创建一个操作
委托,它将知道它的方法,并且编译器能够检查它的正确性。我想到了一个类似于typeof运算符的方法。我不想为了不相关的目的而实例化委托。如果我在代码中看到typeof(类),我想-会有一个反射。如果我看到新的动作(方法),我想会有调用。根据你对Ehsan答案的评论,你会得到什么错误?如果您对编译器错误有疑问,那么它如何知道您将其名称更改为什么方法?这就是为什么您应该使用重构工具来重命名方法,因为没有编译错误。我问的是不同的、更好的解决方案,或者确认当前的解决方案是实现目标的标准方式。听起来你在试图解决一个根本不存在的问题,你的问题非常复杂unclear@Sayse代码正在运行,但我在这里想知道这是否是最好的方法。
private static string GetMethodNameInternal(Type @this, MethodCallExpression bodyExpression)
{
if (bodyExpression == null)
throw new ArgumentException("Body of the exspression should be of type " + typeof(MethodCallExpression).Name);
var member = bodyExpression.Method;
if (member.MemberType != MemberTypes.Method)
throw new ArgumentException("MemberType of the exspression should be of type " + MemberTypes.Method);
if (!object.Equals(@this, member.DeclaringType))
throw new ArgumentException("Invalid property owner.");
return member.Name;
}
var owner = new Foo();
var methodName = typeof(Foo).GetMethodName(() => owner.VoidMethod());
var methodName = typeof(Foo).GetMethodName(() => Foo.StaticVoidMethod());