C# 生成具有方法类型的类的方法列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1198417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate List of methods of a class with method types
提问by cedric
I want to generate a list of all methods in a class or in a directory of classes. I also need their return types. Outputting it to a textfile will do...Does anyone know of a tool, lug-in for VS or something which will do the task? Im using C# codes by the way and Visual Studio 2008 as IDE
我想生成一个类或类目录中所有方法的列表。我还需要他们的返回类型。将它输出到一个文本文件就可以了...有谁知道一个工具,VS 的插件或可以完成任务的东西?我顺便使用 C# 代码和 Visual Studio 2008 作为 IDE
采纳答案by Jon Skeet
Sure - use Type.GetMethods(). You'll want to specify different binding flags to get non-public methods etc. This is a pretty crude but workable starting point:
当然 - 使用 Type.GetMethods()。您需要指定不同的绑定标志来获取非公共方法等。这是一个非常粗略但可行的起点:
using System;
using System.Linq;
class Test
{
static void Main()
{
ShowMethods(typeof(DateTime));
}
static void ShowMethods(Type type)
{
foreach (var method in type.GetMethods())
{
var parameters = method.GetParameters();
var parameterDescriptions = string.Join
(", ", method.GetParameters()
.Select(x => x.ParameterType + " " + x.Name)
.ToArray());
Console.WriteLine("{0} {1} ({2})",
method.ReturnType,
method.Name,
parameterDescriptions);
}
}
}
Output:
输出:
System.DateTime Add (System.TimeSpan value)
System.DateTime AddDays (System.Double value)
System.DateTime AddHours (System.Double value)
System.DateTime AddMilliseconds (System.Double value)
System.DateTime AddMinutes (System.Double value)
System.DateTime AddMonths (System.Int32 months)
System.DateTime AddSeconds (System.Double value)
System.DateTime AddTicks (System.Int64 value)
System.DateTime AddYears (System.Int32 value)
System.Int32 Compare (System.DateTime t1, System.DateTime t2)
System.Int32 CompareTo (System.Object value)
System.Int32 CompareTo (System.DateTime value)
System.Int32 DaysInMonth (System.Int32 year, System.Int32 month)
(etc)
(等等)
回答by David Schmitt
You can get at these lists very easily with reflection. e.g. with Type.GetMethods()
您可以通过反射很容易地获得这些列表。例如与Type.GetMethods()
回答by Arsen Mkrtchyan
using (StreamWriter sw = new StreamWriter("C:/methods.txt"))
{
foreach (MethodInfo item in typeof(MyType).GetMethods())
{
sw.WriteLine(item.Name);
}
}