我有一个类a和一些属性:
abstract class A {
double doubleA;
String stringA;
...
A({this.doubleA = 0, this.stringA = ""});
}
和具有某些属性的类B,它扩展了类a:
class B extends A {
int intB;
String stringB;
B({
this.intB = 0,
this.stringB = "",
double doubleA = 0,
String stringA = "",
}) : super(doubleA: doubleA, stringA: stringA);
}
在我的代码中,我现在想检查A的实例是否具有子类B类型的值:
A a; // Value can be of different subtypes of A including B
if(a is B) {
// here dart should give me access to the properties of a like:
print(a.stringA);
// but it should also be possible to access the type B properties
// since the value of a can also be of subclass type B:
print(a.stringB);
}
这听起来不对,但我知道它可以工作,因为在扑动的例子。
示例侦听器:
Listener(
onPointerSignal: (event) {
// event is of type PointerSignalEvent which has no property 'scrollDelta'.
// So print(event.scrollData); does not work here.
if (event is PointerScrollEvent) {
// if you check if event is of subtype PointerScrollEvent the property 'scrollDelta'
// that is included in the class PointerScrollEvent becomes available.
print(event.scrollDelta); // works without any problem.
}
},
}
然而,我没有能够复制这与我的类A和B,我不知道为什么它不起作用。我还研究了这些颤振类的实现并复制了类结构,但我仍然只能在检查if(a is B)
后访问A
的属性,这与颤振类观察到的行为不一致。
我做错了什么?我错过了什么吗?
感谢阅读:D <3
如果将变量'a'声明为'a'类型,则无法访问继承自a的类(如B)的属性。假设A是动物,B是狒狒。Baboon继承了Animal的属性,所以所有用Baboon类型实例化的变量都可以访问这两个类的属性。但是用Animal类型实例化的变量只能访问Animal属性。下面是一些例子:https://medium.com/jay-tillu/inheritance-in-dart-bd0895883265