在Dart语言中,我如何确定一个对象是否属于某个类?
我想要做类似以下的事情:
if (someObject.class.toString() == "Num") {
...
}
返回值类型是什么?必须是字符串吗?
镜像库一直动荡不定,似乎正在经历快速变化,因为我找到的东西根本就没有按照所示工作。
在Dart语言中,我如何确定一个对象是否属于某个类?
我想要做类似以下的事情:
if (someObject.class.toString() == "Num") {
...
}
返回值类型是什么?必须是字符串吗?
镜像库一直动荡不定,似乎正在经历快速变化,因为我找到的东西根本就没有按照所示工作。
最近,Object
增加了 runtimeType
getter。因此,我们现在不仅可以将对象的类型与另一种类型进行比较,而且可以实际获得对象的 类名。
例如:
myObject.runtimeType.toString()
toString
操作,直接将对象的runtimeType
与目标类型进行比较:myObject.runtimeType == int
myObject.runtimeType == Animal
By using the is
and is!
operators, like this:
if (someObject is T)
From the documentation:
The
is
andis!
operators are handy for checking types. The result ofobj is T
is true ifobj
implements the interface specified byT
. For example,obj is Object
is always true.
Using the Mirrors API (see this example):
Expect.equals('T', someObject.simpleName)
这里有一个简单的解释和解决方案。
你有:
Object obj =t1
;
其中t1
是T类的一个对象。
你还有另一个名为t
的T类对象。
T t = new T()
;
如何检查obj
是否与t
是相同类型的?
解决方案:
if(obj is t)
print('obj is typeof t')
else print('obj is not typeof t')
myObject.runtimeType == int
。 - DanielmyObject is int
相比,有什么优势吗?即使它只实现了其他类型,is
也会返回true,这在某些情况下可能不是期望的结果。有时提到runtimeType
不可靠,因为它可以被覆盖,应仅用于调试目的。 - Günter ZöchbauertestType(object,type) => object.runtimeType == type
。你可以像这样使用它:testType(myObject,int)
。我认为使用is操作符是不可能实现的,但我应该检查一下,也许我错了。 - Vadim Tsushko