简体   繁体   English

使用 System.Reflection 获取方法的全名

[英]Using System.Reflection to Get a Method's Full Name

I have a class that look like the following:我有一个如下所示的类:

public class MyClass
{

...

    protected void MyMethod()
    {
    ...
    string myName = System.Reflection.MethodBase.GetCurrentMethod.Name;
    ...
    }

...

}

The value of myName is "MyMethod". myName值为“MyMethod”。

Is there a way that I can use Reflection to get a value of "MyClass.MyMethod" for myName instead?有没有办法可以使用反射为myName获取“MyClass.MyMethod”的值?

You could look at the ReflectedType of the MethodBase you get from GetCurrentMethod , ie,你可以看一下ReflectedType中的MethodBase你得到GetCurrentMethod ,即

MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;

string fullMethodName = className + "." + methodName;

And to get the full method name with parameters:并获取带参数的完整方法名称:

var method = System.Reflection.MethodBase.GetCurrentMethod();
var fullName = string.Format("{0}.{1}({2})", method.ReflectedType.FullName, method.Name, string.Join(",", method.GetParameters().Select(o => string.Format("{0} {1}", o.ParameterType, o.Name)).ToArray()));

我认为这些天,最好这样做:

string fullMethodName = $"{typeof(MyClass).FullName}.{nameof(MyMethod)}";

Extending Ruben's, you can get the full name like this:扩展鲁本的,你可以得到这样的全名:

var info = System.Reflection.MethodBase.GetCurrentMethod();
var result = string.Format(
                 "{0}.{1}.{2}()",
                 info.ReflectedType.Namespace,
                 info.ReflectedType.Name,
                 info.Name);

You can add it to a static method that receives a MethodBase parameter and generates the string.您可以将其添加到接收 MethodBase 参数并生成字符串的静态方法中。

您可以像这样获得全名:

var fullMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName;

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

string myName = nameof(MyMethod);

Thanks for the posts above, they helped me to create a strong type binding system for MVC 4 HTMLHelpers as follows.感谢上面的帖子,他们帮助我为 MVC 4 HTMLHelpers 创建了一个强大的类型绑定系统,如下所示。

 public static MvcHtmlString StrongTypeBinder(this HtmlHelper htmlhelper, Expression<Func<object, string>> SomeLambda)
    {
        var body = SomeLambda.Body;
        var propertyName = ((PropertyInfo)((MemberExpression)body).Member).Name;
        HtmlString = @"
            <input type='text' name='@Id' id='@Id'/>
            ";
        HtmlString = HtmlString.Replace("@Id", propertyName);
        var finalstring = new MvcHtmlString(HtmlString);
        return finalstring;

    }

To use the code above in any CSHTML View:要在任何 CSHTML 视图中使用上面的代码:

@Html.StrongTypeBinder(p=>Model.SelectedDate)

This allows me to bind any property in a ViewModel to any HTML element type I want.这允许我将 ViewModel 中的任何属性绑定到我想要的任何 HTML 元素类型。 In the example above, I an binding the name field for the selected data posted back after user makes selection.在上面的示例中,我绑定了用户进行选择后回发的所选数据的名称字段。 The viewmodel after the post back automatically shows the selected value.回发后的视图模型会自动显示选定的值。

You'll have issues when running inside async methods.在异步方法中运行时会遇到问题。 Here's how to fix that:以下是解决此问题的方法:

If you need to fully qualify the class name, you'll have to use DeclaringType.FullName instead of DeclaringType.Name如果需要完全限定类名,则必须使用DeclaringType.FullName而不是DeclaringType.Name

This code won't work nicely for anonymous or lambda methods.此代码不适用于匿名或 lambda 方法。

using System.Runtime.CompilerServices;

static string GetMethodContextName() {
    var name = new StackTrace().GetFrame(1).GetMethod().GetMethodContextName();
    return name;
}

static string GetMethodContextName(this MethodBase method) {
    if (method.DeclaringType.GetInterfaces().Any(i => i == typeof(IAsyncStateMachine))) {
        var generatedType = method.DeclaringType;
        var originalType = generatedType.DeclaringType;
        var foundMethod = originalType.GetMethods(
              BindingFlags.Instance | BindingFlags.Static 
            | BindingFlags.Public | BindingFlags.NonPublic 
            | BindingFlags.DeclaredOnly)
            .Single(m => m.GetCustomAttribute<AsyncStateMachineAttribute>()?.StateMachineType == generatedType);
        return foundMethod.DeclaringType.Name + "." + foundMethod.Name;
    } else {
        return method.DeclaringType.Name + "." + method.Name;
    }
}

Here's an example usage:这是一个示例用法:

class Program { 
    static void Main(string[] args) {
        // outputs Program.Main
        Console.WriteLine(GetMethodContextName());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM