获取扩展方法的MethodInfo

chi*_*ef7 4 c# reflection extension-methods

我不能得到扩展方法的方法信息,我怀疑.怎么了?

_toStringMethod = typeof(ObjectExtensions).GetMethod("TryToString",
    BindingFlags.Public | BindingFlags.Static);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

适合我:

using System;
using System.Reflection;

public static class ObjectExtensions
{
    public static string TryToString(this object x)
    {
        // Just guessing...
        return x == null ? "" : x.ToString();
    }
}

class Test
{
    static void Main()
    {
        var method = typeof(ObjectExtensions).GetMethod
            ("TryToString", BindingFlags.Public | BindingFlags.Static);
        // Prints System.String TryToString(System.Object)
        Console.WriteLine(method);
    }
}
Run Code Online (Sandbox Code Playgroud)

你能给出一个类似的简短但完整的例子吗?


Nol*_*rin 2

对我有用。只需检查您的方法类、名称和修饰符是否都正确。

请注意,没有理由它在任何情况下都不起作用。扩展方法仍然是“正常”方法,因为它们属于定义的静态类。只是您访问它们的方式有所不同(当然,尽管您仍然可以正常访问它们)。