继承自c#问题的精神...
在 VB.NET 中,有哪些等效语句可以比较类类型?
你是否在寻找类似于 TypeOf
的东西?这仅适用于引用类型,而不是 int/等。
If TypeOf "value" Is String Then
Console.WriteLine("'tis a string, m'lord!")
或者您想比较两个不同实例的变量吗?对于引用类型也适用:
Dim one As Object = "not an object"
Dim two As Object = "also not an object, exactly"
Dim three as Object = 3D
If one.GetType.Equals( two.GetType ) Then WL("They are the same, man")
If one.GetType Is two.GetType then WL("Also the same")
If one.GetType IsNot three.GetType Then WL("but these aren't")
如果您没有使用两个对象,也可以这样使用gettype()
:
If three.GetType Is gettype(integer) then WL("is int")
如果你想查看某个类型是否是另一个类型的子类(且使用的是 .net 3.5):
If three.GetType.IsSubclassOf(gettype(Object)) then WL("it is")
但是如果你想在早期版本中这样做,你必须翻转它(看起来很奇怪)并使用:
If gettype(Object).IsAssignableFrom(three.GetType) Then WL("it is")
所有这些都可以在SnippetCompiler中编译,如果您没有它,请下载。
TypeOf obj Is MyClass
我不确定VB何时实现了Type.IsInstanceOfType()方法:
"如果当前Type位于由o所表示的对象的继承层次结构中或者当前Type是o实现的接口,则返回true..."
示例:
Dim arr(10) As Integer
If GetType(Array).IsInstanceOfType(arr) Then _
Console.WriteLine("Is int[] an instance of the Array class? {0}.",
GetType(Array).IsInstanceOfType(arr))
int[]是Array类的实例吗?True。
与您链接的问题相对应的VB版本几乎相同:
Dim result As Boolean = obj.GetType().IsAssignableFrom(otherObj.GetType())