Dart/Flutter:检查一个对象的运行时间的多种方法

962 阅读2分钟

本教程展示了如何检查一个对象的运行时间的多种方法。

Runtime type and is operator  Dart and flutter example

在Dart编程中,我们有两种方法可以知道一个对象或一个变量的类型。

这可以检查动态和静态类型,并帮助开发者找到以下东西

  • 检查一个对象的运行时类型
  • 使用is 操作符,对象可以被分配到另一个类型。
  • 检查在Dart或Flutter中声明的一个变量的类型。

runtimeType是一个在超类(Object)中可用的属性实例成员。每个类都继承了Object,所以它默认提供这个属性。

这有助于开发人员获得关于变量或对象类型的调试信息。

下面是语法

Type get runtimeType

这将返回一个静态或动态类型,运行时类型的实例成员在类中不被重写。

例子:

class Employee {}

main() {
  var emp = new Employee();
  var str = "hello";
  var number = 12;
  var float = 12.21;

  List numbers = ["one", "two"];
  print(emp.runtimeType); //Employee
  print(str.runtimeType); //String
  print(number.runtimeType); //int
  print(float.runtimeType); //double
  print(numbers.runtimeType); //JSArray
}

Dart是操作符

is 操作符用于检查一个对象是否是该类型的一个实例。

下面是一个is操作符的例子

让我们创建一个动物父类和两个子类。

class Animal {
  eat() {
    print("Animal Eat");
  }
}

class Lion extends Animal {
  eat() {
    print("Lion Eat");
  }
}

class Dog extends Animal {
  eat() {
    print("Dog Eat");
  }
}

main() {
  Animal animal = new Animal();
  Dog dog = new Dog();

  print(animal.runtimeType); // Animal
  print(dog is Animal); // true
  print(animal is Animal); // true
  print(animal is Dog); // false
}

animal is Animal dog is Animal :返回true,因为动物对象是动物类的类型。animal is Dog :返回false,因为狗是子类型的实例,所以返回true。动物不是类型的子类的类型。 is 如果对象属于同一类型或子类类型,总是返回true。

结论

因此,runtimeType用于检查一个对象的类型,并且总是返回一个字符串。该操作符是用来检查一个特定类型的实例的?这两件事都有助于开发者调试对象的类型,并确定可分配类型的子类型。