Vb.net 带泛型的VB typeof运算符
当在VB中比较类型时,以下操作按预期进行,并允许将当前实例与特定的继承类进行比较,在这种情况下返回Vb.net 带泛型的VB typeof运算符,vb.net,generics,typeof,Vb.net,Generics,Typeof,当在VB中比较类型时,以下操作按预期进行,并允许将当前实例与特定的继承类进行比较,在这种情况下返回False(来自的代码片段) 但是,当引入泛型时,VB编译器会失败,错误类型为“UserQuery.MyBaseClass(of T)”的表达式永远不能是“UserQuery.MyChildClass”类型。 ' Define other methods and classes here MustInherit class MyBaseClass(Of T) Public Function
False
(来自的代码片段)
但是,当引入泛型时,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=新的MyOtherChildClass();
a、 IsType().Dump();
}
//在此处定义其他方法和类
抽象类MyBaseClass
{
公共布尔IsType()
{
返回这是MyChildClass;
}
}
类MyChildClass:MyBaseClass
{
}
类MyOtherChildClass:MyBaseClass
{
}
为什么VB编译器不允许进行这种比较?您提出了一个关于VB/C编译的有趣观点,我对此不敢苟同。如果你在寻找一个解决方案,这里有一个从问题开始的方法 定义这些功能:
Public函数IsSubclassOf(ByVal childType作为类型,ByVal parentType作为类型)作为布尔值
Dim isParentGeneric As Boolean=parentType.IsGenericType
返回IsSubclassOf(子类型、父类型、isParentGeneric)
端函数
私有函数IsubClassof(ByVal childType为类型,ByVal parentType为类型,ByVal isParentGeneric为布尔)为布尔型
如果childType为Nothing,则
返回错误
如果结束
如果isParentGeneric和Also childType.IsGenericType,则
childType=childType.GetGenericTypeDefinition()
如果结束
如果childType是parentType,则
返回真值
如果结束
返回IsSubclassOf(childType.BaseType、parentType、isParentGeneric)
端函数
这样称呼:
Dim baseType As Type=GetType(MyBaseClass(Of))
Dim childType As Type=GetType(MyOtherChildClass)
Console.WriteLine(IsubClassof(childType,baseType))
他写道:没错
下面是一个可以解决这个问题的示例,并解释这是一个特性还是泛型类型的bug
尽管文档中似乎不支持这种情况,但对于类,typeof将在以下情况下返回true:
objectexpression的类型为typename或从typename继承
我熟悉C#,但对VB不太熟悉。但是,示例VB代码和示例C#代码似乎有所不同。在VB示例中,您使用的返回类型Me是MyChildClass
,在C#中是返回类型of(this)是MyChildClass代码>。但是(假定可以工作的)C#示例只返回了这是MyChildClass代码>
我希望TypeOf Me Is MyChildClass
询问左侧的实例表达式(即Type
)是否可以分配给右侧声明为类型的变量(MyChildClass
)。由于框架类Type
与您的MyChildClass
没有连接,这是不可能的,因此编译器可能会发现一个警告或错误——可能就是您得到的警告或错误
相反,我认为VB代码应该是Return Me Is MyChildClass
,以匹配C#示例,C#示例应该正确询问实例Me是否可以分配给声明为MyChildClass
的变量。如果使用这种语法,VB还会反对吗?或者,这会修复错误并获得正确的行为吗
' 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