1

跟进一个较早的 SO 问题,现在我想将其收集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这个篮子?

4

1 回答 1

1

快速破解(除非存在实际解决方案)将发送一个元组到basket元组代表的位置(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]对象内容。

要访问诸如poisoncolor之后的类变量,您可以执行以下操作

if (b[1] == "Banana") {
    var obj = b[2]: Banana;
    writeln(obj.color);
}

和类似的类Apple

于 2017-08-29T17:09:34.323 回答