[英]What is the VB equivalent of Java's instanceof and isInstance()?
您在寻找类似TypeOf
的东西吗? 这只适用于引用类型,不适用于 int/etc。
If TypeOf "value" Is String Then
Console.WriteLine("'tis a string, m'lord!")
或者您想比较两个不同的变量实例? 也适用于 ref 类型:
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中编译,所以 go DL 如果你没有的话。
TypeOf obj Is MyClass
不确定它是什么时候实现的,但 VB 现在有Type.IsInstanceOfType() :
“如果当前类型在 o 表示的 object 的 inheritance 层次结构中,或者如果当前类型是 o 实现的接口,则返回真...”
例子:
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))
Output: Is int[] an instance of the Array class? True.
Is int[] an instance of the Array class? True.
与您的链接问题等效的 VB 几乎相同:
Dim result As Boolean = obj.GetType().IsAssignableFrom(otherObj.GetType())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.