Inheritance 如何在Dart中指定给基类变量的对象中检测接口?

Inheritance 如何在Dart中指定给基类变量的对象中检测接口?,inheritance,interface,dart,Inheritance,Interface,Dart,考虑这样的类层次结构: 只有一个基类,BaseClass 有许多来自基类的派生类,其中一些实现了不同的接口 例如,有一个类DerivedClass,它扩展了BaseClass,并实现了SomeInterface 因为我处理的是许多不同的类,它们都继承自基类,所以我想我应该将它们的对象存储在一个容器中,比如列表。但我似乎无法找到一种方法来检测这些对象中的接口 class SomeInterface { String field; } abstract class BaseClass {

考虑这样的类层次结构:

  • 只有一个基类,
    BaseClass
  • 有许多来自
    基类的派生类,其中一些实现了不同的接口
例如,有一个类
DerivedClass
,它扩展了
BaseClass
,并实现了
SomeInterface

因为我处理的是许多不同的类,它们都继承自
基类
,所以我想我应该将它们的对象存储在一个容器中,比如
列表
。但我似乎无法找到一种方法来检测这些对象中的接口

class SomeInterface {
  String field;
}

abstract class BaseClass {
  int count;

  BaseClass(this.count);
}

class DerivedClass extends BaseClass implements SomeInterface {
  String field;

  DerivedClass(int count, this.field) : super(count);
}

void printField(SomeInterface obj) {
  print(obj.field);
}

void main() {
  BaseClass item = DerivedClass(4, 'test');
  if (item is SomeInterface) {  // Attempt one
    print(item.field);
  }
  printField(item);  // Attempt two
}

早些时候,我在继承链中有
SomeInterface
,就像一个实际的超类,但我不想这样,因为在我的例子中,接口更容易处理。您有什么建议吗?

对于实现的接口和超级类一样有效

所以

这是一条路要走

正如@attdona在下面指出的,要在
is
之后访问
SomeInterface
成员,仍然需要检查cast

另见


项目
必须使用
作为操作员进行铸造:
打印((项目作为SomeInterface).field)我明白了。我真的不明白这个问题是关于什么的。我认为当
item
是一个变量时,它不应该是必需的,因为它不能在后续访问之间更改类型。如果
item
是一个getter,那就不一样了
if (item is SomeInterface) {