在Dart中,类只扩展了一个父类,并实现了多个接口。
下面是检查一个给定对象的类的操作符:
is 检查一个给定的对象是否实现或扩展了接口或类,它检查父类的层次结构,如果它遵循继承,则返回true。
runtimeType:返回一个对象的类,并给出一个对象的唯一当前类,而不是继承树类。
在Dart中检查一个对象是否实现了接口?
这个例子检查一个对象是否实现了接口。
在这个例子中,创建了两个接口Shape 和Shape1 。
创建一个实现多个接口的Square 类(Shape,Shape1) 创建一个实现单个接口的Circle (Shape)
使用Dart中的is 操作符来检查一个对象是否实现了一个特定的接口。
下面是一个示例程序
void main() {
var square = new Square();
var circle = new Circle();
print(square is Shape); //true
print(square is Shape1); //true
print(square.runtimeType); //Square
print(circle is Shape); //true
print(circle.runtimeType); //Circle
}
abstract class Shape {
void display() {
print("Shape");
}
}
abstract class Shape1 {
void display() {
print("Shape");
}
}
class Circle implements Shape {
void display() {
print("Circle");
}
}
class Square implements Shape, Shape1 {
void display() {
print("Square");
}
}
输出
true
true
Square
true
Circle
如何在Dart中检查Object extends class?
这将检查一个给定的对象是否扩展了类。
在这个例子中,创建了两个接口Animal 和Animal 。
创建一个Lion ,该类实现了Class(Animal),因为在dart中隐含的类是一个接口。创建Cat ,扩展一个单一的接口(Animal)
使用Dart中的is 操作符来检查一个对象是否扩展了一个特定的类。
下面是一个示例程序
void main() {
var lion = new Lion();
var cat = new Cat();
print(lion is Animal); //true
print(lion is Animal1); //false
print(lion.runtimeType); //Lion
print(cat is Lion); //true
print(cat.runtimeType); //Cat
}
class Animal {
void display() {
print("Animal");
}
}
class Animal1 {
void display() {
print("Shape");
}
}
class Lion implements Animal {
void display() {
print("Lion");
}
}
class Cat extends Animal1 {
void display() {
print("Cat");
}
}