检索所有方法名



我试图在所有反射类中获得我的所有方法。这是我的代码。我可以得到类名,但我不能得到方法名。我怎么能做到呢?

string @namespace = "Application.Main";
List<String> methodNames = new List<string>();
List<String> appServiceClasses = new List<string>();
List<Type> returnVal = AppDomain.CurrentDomain
                                .GetAssemblies()
                                .SelectMany(t => t.GetTypes())
                                .Where(t => t.IsClass && t.Namespace == @namespace).ToList();
for (int i = 0; i < returnVal.Count; i++)
{
    appServiceClasses.Add(returnVal[i].Name);
}
Type myTypeObj = typeof(appServiceClasses[0]);
MethodInfo[] methodInfos = myTypeObj.GetMethods();
foreach (MethodInfo methodInfo in methodInfos)
{
    string a = methodInfo.Name;
}

好吧,你已经有你的类的类型,为什么你得到他们的名字?我是说这样做的目的是什么?你可以使用这些类型实例来获取你的方法。

var methods = returnVal.SelectMany(x => x.GetMethods());

Edit:您还可以使用Dictionary<string, MethodInfo[]>,以便您可以访问类的方法so,其名称如下:

var methods = returnVal.ToDictionary(x => x.Name, x => x.GetMethods());
var methodsOfFoo = methods["Foo"];

使用类型来请求方法:

for (int i = 0; i < returnVal.Count; i++)
{
  appServiceClasses.Add(returnVal[i].Name);
  MethodInfo[] methodInfos = returnVal[i].GetMethods();
  foreach (MethodInfo methodInfo in methodInfos)
  {
    string a = methodInfo.Name;
  }
}

您不需要存储类型名称,然后使用typeof。你已经有了类型:-

var appServiceClassTypes = AppDomain.CurrentDomain.GetAssemblies()
                                    .SelectMany(x => x.GetTypes())
                                    .Where(x => x.IsClass && x.Namespace == ...)
                                    .ToList();
var appServiceClasses = appServiceClassTypes.Select(x => x.Name);
var methodNames = appServiceClassTypes.SelectMany(x => x.GetMethods())
                                      .Select(x => x.Name)
                                      .ToList();

如果你实际上不需要appServiceClasses集合的任何地方,你应该只是能够链在一起:-

var methodNames = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(x => x.GetTypes())
                           .Where(x => x.IsClass && x.Namespace == ...)
                           .SelectMany(x => x.GetMethods())
                           .Select(x => x.Name)
                           .ToList();

你可能想知道哪个方法属于哪个类:-

var methods = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .Where(x => x.IsClass && x.Namespace == ...)
                       .Select(x => new Tuple<string, IEnumerable<string>>(
                           x.Name,
                           x.GetMethods().Select(y => y.Name)));

或:-

var methods = AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(x => x.GetTypes())
                       .Where(x => x.IsClass && x.Namespace == ...)
                       .ToDictionary(
                           x => x.Name,
                           x => x.GetMethods().Select(y => y.Name));

相关内容

  • 没有找到相关文章

最新更新