如何确定一种方法“是否是类型的扩展方法?”

时间:2011-07-24 13:36:28

标签: c#-4.0

我想写一个名为IsExtensionMethod的方法,它的签名是:

public bool IsExtensionMethod(object anObject, string method)
{
    // if method was an extension for anObject return true else false
}

我该怎么做?

我尝试使用以下代码,但在某些情况下,它的返回值不正确:

public bool IsExtensionMethod(object anObject, string method)
{
    return anObject.GetType().GetMethods().Where(item => item.Name == method).Count() == 0;
}

1 个答案:

答案 0 :(得分:2)

编译器在编译扩展方法时会向扩展方法添加CompilerServices.ExtensionAttribute属性。寻找这个属性。

http://www.hanselman.com/blog/HowDoExtensionMethodsWorkAndWhyWasANewCLRNotRequired.aspx