1

Maybe this is not a Dart specific question.

I have :

class A {
  int a;

  A(this.a);
}

class B extends A {
  String b;

  B(a, this.b) : super(a);
}

So you see, class A has an attribute int a and B just extends A and has an extra attribute String b and a wrapper class C :

class C {
  A c;

  C(this.c);

  void doSomething() {
    if (c is B) {
      print(c.b);
    } else {
      print(c.a);      
    }
  }

}

The Dart Editor complaints that the c doesn't have a getter b. How do you deal with this? I want to get rid the warning, but I don't want to add attribute b to class A

4

3 回答 3

2

The analyzer shouldn't add a warning here. I think it's related to this issue : Analyzer fails to respect certain "is" checks.

In the meanwhile, you can use (c as B).b to cast c in B.

于 2013-06-24T12:55:31.797 回答
2

(c as B) works, but will do a dynamic type check (which will probably be eliminated by the VM).

If you just want to remove the warning, without changing the semantics of the program you can assign to a temporary variable of the correct type:

void doSomething() {
  if (c is B) {
    B b = c;
    print(b.b);
  } else {
    print(c.a);
  }
}
于 2013-06-24T13:59:18.073 回答
1

You can cast expression.

print((c as B).b);
于 2013-06-24T12:38:48.500 回答