How I can find all extension methods in solution?

2020-05-21 05:06发布

How I can find all extension methods in solution ?

5条回答
地球回转人心会变
2楼-- · 2020-05-21 05:20

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;
}
查看更多
相关推荐>>
3楼-- · 2020-05-21 05:33

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"
查看更多
何必那么认真
4楼-- · 2020-05-21 05:35

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

查看更多
We Are One
5楼-- · 2020-05-21 05:41

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)?

查看更多
啃猪蹄的小仙女
6楼-- · 2020-05-21 05:47

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.

查看更多
登录 后发表回答