I don't know Dart, but this wouldn't be valid in C# either, and I'd expect the reason to be the same.
Suppose you had this code (apologies for any invalid syntax):
class D extends A {}
var c = C<D>();
Within the context of that new object, the relevant T
is D
- it's an instance of C<D>
. So your test
method logically expects a D
... but you're providing it a B
. Suppose your test
method stored that value, and then another method returned it later as a T
- then you could have:
var c = C<D>();
var d = c.getValue();
That code would expect the return value of getValue()
to be a D
, but it would actually be a B
.
I don't know enough about Dart to know why the cast removes the error, but it looks to me like your code is fundamentally dangerous and could fail at some point in the kind of scenario I described above. I suspect you need to redesign the code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…