【问题标题】:How to get Method name in c# as a string? [duplicate]如何在 c# 中将方法名称作为字符串获取? [复制]
【发布时间】:2020-06-24 14:58:16
【问题描述】:

在 Java 中,我们可以使用 java.lang.reflect API 中的 Method 来获取方法名称。例如

public void GetmethodName(Method method)
{
  String testName = method.getName();

}

我可以使用 c# 中的反射 API 或诊断 API 来实现这一点

【问题讨论】:

  • 这里testName的期望值是多少?我不想做任何假设,虽然我认为我知道你在追求什么。
  • 不要在 C# 6 及更高版本中使用反射,改用nameof(MethodName)
  • @Fixation 哦,很多时候基于MethodInfo 的反射是完全合适的;真的取决于上下文(我们这里没有)
  • 我明白这一点,但我不明白为什么我们在提及nameof() 之前建议进行反思。

标签: c#


【解决方案1】:

非常相似:

public void GetMethodName(MethodInfo method)
{
  string testName = method.Name;
}

您可以通过Type 实例获取MethodInfo,即typeof(Foo).GetMethod(...)someTypeInstance.GetMethods(...)

【讨论】:

    【解决方案2】:

    你可以使用CallerMemberNameAttribute

    public void GetmethodName([CallerMemberName] string methodname = null)
    {
      Console.WriteLine(methodname);
    }
    

    使用CallerMemberNameAttribute时,编译器在编译时直接硬编码(检查ldstr指令)方法名,不需要反射。例如,

    void Foo()
    {
        GetmethodName();
    }
    

    查看 IL 代码

    IL_0000:  nop         
    IL_0001:  ldarg.0     
    IL_0002:  ldstr       "Foo"
    IL_0007:  call        UserQuery.GetmethodName
    IL_000C:  nop         
    IL_000D:  ret    
    

    【讨论】:

    • IL 看起来像是处于调试模式;没有它会更简洁,特别是如果你让GetmethodName static
    • @MarcGravell 不错,没错。它处于调试模式。
    【解决方案3】:

    可以使用反射获取方法名称:

    using System.Reflection;
    
    // ...
    
    public class MyClass
    {    
        public void MyMethod()
        {
            MethodBase m = MethodBase.GetCurrentMethod();
    
            // This will write "MyClass.MyMethod" to the console
            Console.WriteLine($"Executing {m.ReflectedType.Name}.{m.Name}");
        }
    }
    

    【讨论】:

    • 如果你在 current 方法的名字之后,你不会那样做;您只需编写 static string CurrentMethodName([CallerMemberName] string caller = null) => caller; 并执行 string whoAmI = CurrentMethodName(); - 或只是 string whoAmI = nameof(TheMethodYouAreIn); (如果您只想避免使用字符串文字)
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多