从另一个程序集中获取类和方法

时间:2014-01-08 21:13:38

标签: c# .net .net-assembly

我有2个Proyects的解决方案:

  • __ mvc4
  • getClassesMethods

getClassesMethods引用了__mvc4,所以我想从__mvc4项目中的命名空间中获取所有类和方法,所以我有这个代码加载并从AppDomain获取所有程序集

这是var asssemblies的断点(包含__mvc4程序集)

enter image description here

    namespace getClassesMethods
    {
        class Program
        {
            static void Main(string[] args)
            {


                var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
                var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();

                var referencedPaths = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
                var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();
                toLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));

                var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

但我不知道如何从var程序集中的___mvc4程序集中获取所有类和方法。希望你能帮助我!

2 个答案:

答案 0 :(得分:2)

只是一个样本

foreach(var asm in loadedAssemblies)
{
   var classes = asm.GetTypes(); // you can use GetTypes to get all classes in that assembly
   foreach(var c in classes)
   {
      // you can get all methods which is defined in this class with GetMethods
      var methods = c.GetMethods();

      // or you can get all properties defined in this class
      var props = c.GetProperties();
   }
}  

有关详细信息,请参阅Type课程并阅读此documentation

答案 1 :(得分:1)

尝试:

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm=>asm.GetTypes());
var methods = types.SelectMany(type=>type.GetMethods());

注意

“类”在.NET中称为“类型”。