2009-06-12 79 views
2

我无法获得扩展方法的方法信息,因为我怀疑。怎么了?获取扩展方法的MethodInfo

_toStringMethod = typeof(ObjectExtensions).GetMethod("TryToString", 
    BindingFlags.Public | BindingFlags.Static); 
+0

是的,绝对没有任何关系的扩展方法本身。 – Noldorin 2009-06-12 16:58:15

回答

2

适合我。只要检查你的方法类,名称和修饰符都是正确的。

作为一个说明,没有任何理由不应该在任何情况下工作。扩展方法仍然是“常规”方法,因为它们属于定义的静态类。只有访问它们的方式不同(当然,您仍然可以访问它们)。

4

工作对我来说:

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); 
    } 
} 

你能给它失败了类似短,但完整的例子吗?

0

我无法得到我的代码扩展方法太 这只是我的一个命名空间冲突,而不是我的推广类 它使用的EntityFramework的扩展类,所以我必须明确地键入

typeof(MyAppNamespace.Extensions).GetMethod(...) 

代替:

typeof(Extensions).GetMethod(...)