How I can find all extension methods in solution?

我们两清 提交于 2019-12-03 00:07:55

If I were doing it I would search all files for the string "( this " -- your search string may differ based on your formatting options.

EDIT: After a little bit of experimentation, the following seems to work for me with high precision using "Find in Files" (Ctrl-Shift-F)

  • Search string: "\( this [A-Za-z]" (minus quotes, of course)
  • Match case: unchecked
  • Match whole word: unchecked
  • Use: Regular Expressions
  • Look at these file types: "*.cs"

I'd look at the generated assemblies using reflection; iterate through the static types looking for methods with [ExtensionAttribute]...

static void ShowExtensionMethods(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
    {
        if (type.IsClass && !type.IsGenericTypeDefinition
            && type.BaseType == typeof(object)
            && type.GetConstructors().Length == 0)
        {
            foreach (MethodInfo method in type.GetMethods(
                BindingFlags.Static |
                BindingFlags.Public | BindingFlags.NonPublic))
            {
                ParameterInfo[] args;

                if ((args = method.GetParameters()).Length > 0 &&
                    HasAttribute(method,
                      "System.Runtime.CompilerServices.ExtensionAttribute"))
                {
                    Console.WriteLine(type.FullName + "." + method.Name);
                    Console.WriteLine("\tthis " + args[0].ParameterType.Name
                        + " " + args[0].Name);
                    for (int i = 1; i < args.Length; i++)
                    {
                        Console.WriteLine("\t" + args[i].ParameterType.Name
                            + " " + args[i].Name);
                    }
                }
            }
        }
    }
}
static bool HasAttribute(MethodInfo method, string fullName)
{
    foreach(Attribute attrib in method.GetCustomAttributes(false))
    {
        if (attrib.GetType().FullName == fullName) return true;
    }
    return false;
}

Maybe the code in this article about how to find extension methods targeting object could be used? Could for example be rewritten slightly and use it to dump all extension methods instead of just those targeting object.

Dario

Do you just want to check the sourcecode (just look for (this ... in the files) or your running programm by reflection (in this case, this this discussion can help you)?

Solution wide text search with a regex matching your coding style. Something like "( *this +" (added the first optional space to get some error tollerance).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!