跟进earlier SO question,现在我想将Fruit
收集到一个篮子中,但在出路时知道子类型。
class Banana : Fruit {
var color: string;
}
class Apple: Fruit {
var poison: bool;
}
class Fruit {
}
var a = new Apple(poison=true);
var b = new Banana(color="green");
if (a.type == Apple) {
writeln("Go away doctor!");
}
var basketDom = {1..1};
var basket: [basketDom] Fruit;
basket.push_back(a);
basket.push_back(b);
for b in basket {
writeln(b.type:string);
}
这将打印超类型Fruit
。如何从这个购物篮中获取Apples
和Bananas
?
答案 0 :(得分:1)
快速破解(除非存在实际解决方案)将元组发送到元组代表basket
的{{1}}。
您的代码将成为,
(type_of_object, typecasted_object)
这会给你
var basketDom = {1..1};
var basket: [basketDom] (string, Fruit);
basket.push_back((a.type:string, a));
basket.push_back((b.type:string, b));
for b in basket {
writeln(b);
}
此外,您可以使用索引访问类型。例如 - (Apple, {poison = true})
(Banana, {color = green})
将是对象内容的类型和b[1]
。
要在此之后访问类变量,例如b[2]
和poison
,您可以执行类似
color
并且类似于if (b[1] == "Banana") {
var obj = b[2]: Banana;
writeln(obj.color);
}
课程。