vb.net - 带有泛型的 VB typeof 运算符

标签 vb.net generics typeof

在 VB 中比较类型时,以下内容按预期工作,并使当前实例与特定的继承类进行比较,在本例中返回 False(来自 LINQPad 的片段)

Sub Main
    Dim a As New MyOtherChildClass

    a.IsType().Dump()
End Sub

' Define other methods and classes here
MustInherit class MyBaseClass
    Public Function IsType() As Boolean
        Return TypeOf Me Is MyChildClass
    End Function
End Class

Class MyChildClass 
    Inherits MyBaseClass
End Class

Class MyOtherChildClass
    Inherits MyBaseClass
End Class

但是,当引入泛型时,VB 编译器会失败,并显示错误“UserQuery.MyBaseClass(Of T)”类型的表达式永远不能是“UserQuery.MyChildClass”类型。

' Define other methods and classes here
MustInherit class MyBaseClass(Of T)
    Public Function IsType() As Boolean
        Return TypeOf Me Is MyChildClass
    End Function
End Class

Class MyChildClass 
    Inherits MyBaseClass(Of String)
End Class

Class MyOtherChildClass
    Inherits MyBaseClass(Of String)
End Class

C#中的等效代码编译并允许比较,返回正确的结果

void Main()
{
    var a = new MyOtherChildClass();

    a.IsType().Dump();
}

// Define other methods and classes here

abstract class MyBaseClass<T>
{
    public bool IsType()
    {
        return this is MyChildClass;
    }
}

class MyChildClass : MyBaseClass<string>
{
}

class MyOtherChildClass : MyBaseClass<string>
{
}

为什么 VB 编译器不允许这种比较?

最佳答案

你提出了一个关于 VB/C# 编译的有趣观点,但我实在无法谈论。如果您正在寻找解决方案,可以通过问题 How can I recognize a generic class? 来实现此目的。

定义这些函数:

Public Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type) As Boolean
    Dim isParentGeneric As Boolean = parentType.IsGenericType

    Return IsSubclassOf(childType, parentType, isParentGeneric)
End Function

Private Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type, ByVal isParentGeneric As Boolean) As Boolean
    If childType Is Nothing Then
        Return False
    End If

    If isParentGeneric AndAlso childType.IsGenericType Then
        childType = childType.GetGenericTypeDefinition()
    End If

    If childType Is parentType Then
        Return True
    End If

    Return IsSubclassOf(childType.BaseType, parentType, isParentGeneric)
End Function

这样调用:

Dim baseType As Type = GetType(MyBaseClass(Of ))
Dim childType As Type = GetType(MyOtherChildClass)

Console.WriteLine(IsSubclassOf(childType, baseType))
'Writes: True

这是一个Microsoft Connect Ticket这可能会解决这个问题,并给出一些解释,说明这是通用类型的功能还是错误。

虽然 Type Of 似乎不支持这种情况文档指出,对于类,如果满足以下条件,typeof 将返回 true:

objectexpression is of type typename or inherits from typename

关于vb.net - 带有泛型的 VB typeof 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18245719/

相关文章:

c# - C# 中的 Utils.CopyArray?

.net - 如何使用 VB.NET 编译 VB.NET 控制台应用程序的源代码

vb.net - 使用 Visual Studio Designer 时,如何将 WinForms 控件的类型更改为从原始类型派生的新类型?

vb.net - 在 vb.net 中按不同对象属性对自定义对象列表进行多次排序

java - 关于Java泛型的查询

swift - 如何使用范围进行泛型处理?

对具有通用类型约束的 Observable 的 Swift 扩展

javascript - 在 Javascript 中检查数组的所有元素类型时出现问题

javascript - JavaScript 中的 new String ("x") 有什么意义?

javascript - 测试 XML 元素是否存在时遇到问题