How I can find all extension methods in solution ?
问题:
回答1:
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"
回答2:
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:
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
.
回答4:
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)?
回答5:
Solution wide text search with a regex matching your coding style. Something like "( *this +"
(added the first optional space to get some error tollerance).