【问题标题】:.NET: Get all classes derived from specific class.NET:获取从特定类派生的所有类
【发布时间】:2011-06-30 00:57:03
【问题描述】:

我有一个自定义控件和许多从它派生的控件。 我需要获取当前程序集中从主类派生的所有类并检查它们的属性。 如何做到这一点?

【问题讨论】:

    标签: .net oop reflection inheritance attributes


    【解决方案1】:
    var type = typeof(MainClass);
    
    var listOfDerivedClasses = Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(x => x.IsSubclassOf(type))
        .ToList();
    
    foreach (var derived in listOfDerivedClasses)
    {
       var attributes = derived.GetCustomAttributes(typeof(TheAttribute), true);
    
       // etc.
    }
    

    【讨论】:

    • 请注意,在上面的代码中假设 MainClass 位于当前正在执行的程序集 (Assembly.GetExecutingAssembly) 中。如果不是,您将遇到问题。
    • @Brady,不正确。此代码在当前执行的程序集中查找派生自 MainClass 的类型——它们可以在同一个程序集中或不同的程序集中:没关系。
    【解决方案2】:

    你可以使用反射:

    Type baseType = ...
    var descendantTypes =
        from type in baseType.Assembly.GetTypes()
        where !type.IsAbstract
           && type.IsSubclassOf(baseType)
           && type.IsDefined(typeof(TheCustomAttributeYouRequire), true)
        select type;
    

    你可以从那里去。

    【讨论】:

    • 为什么是 !t​​ype.IsAbstract?抽象类仍然可以是从另一个类派生的类。
    【解决方案3】:

    为了找到一个类的派生类,这些派生类都是在另一个程序集中定义的(GetExecutingAssembly 不起作用),我使用了:

    var asm = Assembly.GetAssembly(typeof(MyClass));
    var listOfClasses = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(MyClass)));
    

    (分成两行以节省滚动)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多