【问题标题】:Dart create instance using super class objectDart 使用超类对象创建实例
【发布时间】:2019-12-14 07:12:03
【问题描述】:

是否可以用它的超类的实例来构造一个类的实例而不用一个一个地调用每个字段(在下面的代码中,我调用bar.name)?

当我这样做时,Foo foo = bar,我得到

Instance of 'Bar': type 'Bar' is not a subtype of type 'Foo'

不过,Foo 扩展了 bar

void main() {
 Bar bar = Bar('bar');
  Foo foo2 = Foo(null, bar.name); // Works but need to call every field 
  print(foo2.name);

  Foo foo = bar; // How to make this work ?
}
class Bar{
  final String name;
  Bar(this.name);
}
class Foo extends Bar{
  final int age;
  Foo(this.age, String name) :super(name);
}

【问题讨论】:

  • 你为什么要这么做?

标签: dart


【解决方案1】:

这是不可能的,因为它没有感觉。 FooBar(它扩展了 Bar),但 Bar 不是 Foo。所以你不能把它分配给Foo

确实,由于Foo 扩展了BarBar 中缺少的东西在Foo 中存在。

回到你原来的问题,如果你想创建一个没有ageFoo,你可以这样做:

class Foo extends Bar{
  final int age;
  Foo(this.age, String name) :super(name);

  factory Foo.withoutAge(String name) => Foo(null, name);
}

void main() {
  Foo foo2 = Foo.withoutAge('bar'); 
  print(foo2.name);
}

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多