如何判断一个对象是否属于某个类的实例

43

在Dart语言中,我如何确定一个对象是否属于某个类?

我想要做类似以下的事情:

if (someObject.class.toString() == "Num") {
    ...
}

返回值类型是什么?必须是字符串吗?


镜像库一直动荡不定,似乎正在经历快速变化,因为我找到的东西根本就没有按照所示工作。

3个回答

57

最近,Object 增加了 runtimeType getter。因此,我们现在不仅可以将对象的类型与另一种类型进行比较,而且可以实际获得对象的 类名

例如:

myObject.runtimeType.toString()

此外,在当前版本的Dart中,您可以跳过toString操作,直接将对象的runtimeType与目标类型进行比较:
myObject.runtimeType == int

或者
myObject.runtimeType == Animal

1
可以直接比较,例如 myObject.runtimeType == int - Daniel
2
myObject is int相比,有什么优势吗?即使它只实现了其他类型,is也会返回true,这在某些情况下可能不是期望的结果。有时提到runtimeType不可靠,因为它可以被覆盖,应仅用于调试目的。 - Günter Zöchbauer
1
我认为使用runtimeType相比较于is操作符会给你更多的动态能力。例如看一下这个函数:testType(object,type) => object.runtimeType == type。你可以像这样使用它:testType(myObject,int)。我认为使用is操作符是不可能实现的,但我应该检查一下,也许我错了。 - Vadim Tsushko
2
我已经确认了,我的猜测是正确的。你不能将“类型字面量”作为函数参数传递,然后在“is”操作中使用它。因此,“isOfType(obj,Type type)= > obj is type”是不正确的,但是“isOfType(obj,Type type)= > obj.runtimeType == type”可以正常工作。 - Vadim Tsushko
更好的答案还没有。 - Pushan Gupta
2
如果您在Web上使用Dart,则将代码缩小为JS代码将返回缩小的值! - Zufar Muhamadeev

51
  • By using the is and is! operators, like this:

    if (someObject is T)
    

    From the documentation:

    The is and is! operators are handy for checking types. The result of obj is T is true if obj implements the interface specified by T. For example, obj is Object is always true.

  • Using the Mirrors API (see this example):

    Expect.equals('T', someObject.simpleName)
    

1
谢谢!运行得非常好。请参见下面的快速测试:bool noteIsString(var note) { return( note is String );}bool test0 = noteIsString("string");bool test1 = noteIsString(123.45);print("test0 result is: $test0"); //=> trueprint("test1 result is: $test1"); //=> false - george koller

0

这里有一个简单的解释和解决方案。

你有:

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') 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接