【问题标题】:How can I know the classes that extend my base class at runtime? [duplicate]我如何知道在运行时扩展我的基类的类? [复制]
【发布时间】:2014-07-28 16:22:13
【问题描述】:

在运行时期间,我想用扩展了我的基类的类填充下拉列表。目前我有一个枚举,这就是我用来填充该列表的内容,但我想添加其他类(并且其他人正在添加类)并且不想为此维护一个枚举。我想添加一个新类,并且神奇地(可能是反射)该类出现在列表中,而没有为下拉列表编写任何添加代码或添加任何额外的枚举。

class Animal { ... }

enum AllAnimals { Cat, Dog, Pig };
class Cat : Animal {...}
class Dog : Animal {...}
class Pig : Animal {...}

有没有办法做到这一点?

【问题讨论】:

  • 请不要只要求我们为您解决问题。向我们展示您如何尝试自己解决问题,然后向我们确切地展示结果是什么,并告诉我们您为什么觉得它不起作用。请参阅“What Have You Tried?”了解您真正需要阅读的优秀文章。
  • 是的,有办法做到这一点。请使用 Google 并自己尝试一下。然后,如果它不起作用,请返回您的代码和您收到的错误消息,我们会尽力提供帮助。
  • 派生类是否都保证在同一个程序集中?

标签: c# reflection enums polymorphism extending


【解决方案1】:

使用反射获取加载的程序集,然后枚举作为基类子类的所有类型。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var types = new List<Type>();

            foreach (var assembly in assemblies)
                types.AddRange(assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Animal))));

            foreach (var item in types)
                Console.WriteLine(item.Name);
        }
    }

    class Animal { }

    enum AllAnimals { Cat, Dog, Pig };
    class Cat : Animal { }
    class Dog : Animal { }
    class Pig : Animal { }
}

【讨论】:

  • 为什么要再次加载程序集?它已经加载了。这也假设所有子类都在同一个程序集中。
  • 我已经更新了示例。
猜你喜欢
  • 1970-01-01
  • 2012-10-18
  • 2019-12-22
  • 1970-01-01
  • 2013-10-14
  • 2012-01-15
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多