Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 在不明确了解子类的情况下列出子类_Vb.net_Oop_Inheritance - Fatal编程技术网

Vb.net 在不明确了解子类的情况下列出子类

Vb.net 在不明确了解子类的情况下列出子类,vb.net,oop,inheritance,Vb.net,Oop,Inheritance,假设我有一个抽象类IceCream,VanillaIceCream和StrawberryICream继承自该类。我还有一个IceCreamView,它引用了抽象类IceCream(即,仅使用所有类型冰淇淋的通用属性)。但是,我还需要在视图中实现一个组合框,用户可以在其中选择他们想要创建的冰淇淋类型;可用类型应由冰淇淋的子类决定 我的问题是:是否有任何方法可以在这个视图中列出冰激凌的所有子类,而不必在抽象超类和视图中明确知道它们 我的问题的背景是,我希望将来能够在不更改现有代码的情况下扩展功能(添

假设我有一个抽象类IceCream,VanillaIceCream和StrawberryICream继承自该类。我还有一个IceCreamView,它引用了抽象类IceCream(即,仅使用所有类型冰淇淋的通用属性)。但是,我还需要在视图中实现一个组合框,用户可以在其中选择他们想要创建的冰淇淋类型;可用类型应由冰淇淋的子类决定

我的问题是:是否有任何方法可以在这个视图中列出冰激凌的所有子类,而不必在抽象超类和视图中明确知道它们

我的问题的背景是,我希望将来能够在不更改现有代码的情况下扩展功能(添加更多类型的冰淇淋)

我提出的唯一能打破这一假设的解决方案是: 1) 在视图中手动输入子类的名称。 2) 在视图中引用子类而不是(/除了)抽象超类。
3) 在超类中创建一个枚举,列出所有子类。

这取决于您使用的语言。一些语言使其在运行时易于检查,另一些语言使每个具体类注册自己变得足够容易,还有一些语言具有完全新颖的特性。那么你在写什么,比一些有继承性的语言更具体,可能使用“超级/子类”的命名法?你需要使用反射。使用以下方法:

''' <summary>
''' Retrieves all subclasses of the specified type.
''' </summary>
''' <param name="baseType">The base type.</param>
''' <param name="onlyDirectSubclasses">Indicates whether only the direct subclasses
''' should be retrieved. If set to <see langword="false"/>, then all, also
''' indirect subclasses will be retrieved.</param>
''' <returns></returns>
''' <remarks></remarks>
Function GetSubclasses(ByVal baseType As Type, ByVal onlyDirectSubclasses As Boolean) As List(Of Type)
    Dim res As New List(Of Type)

    For Each asm As Reflection.Assembly In AppDomain.CurrentDomain.GetAssemblies()
        For Each typ As Type In asm.GetTypes()
            If onlyDirectSubclasses Then
                If typ.BaseType Is baseType Then
                    res.Add(typ)
                End If
            Else
                If typ.IsSubclassOf(baseType) Then
                    res.Add(typ)
                End If
            End If
        Next
    Next

    Return res
End Function

在这种情况下,我使用的是VB.NET。
Dim subclasses As List(Of Type) = GetSubclasses(GetType(IceCream), False)