如何维护 Chapel 数组中对象的子类型
How to maintain sub-type of an object in a Chapel array
跟进 ,现在我想将 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
?
快速破解(除非存在实际的解决方案)会将一个元组发送到 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]
是对象内容。
在此之后要访问 class 变量,例如 poison
和 color
,您可以执行类似
的操作
if (b[1] == "Banana") {
var obj = b[2]: Banana;
writeln(obj.color);
}
和 class Apple
.
类似
跟进 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
?
快速破解(除非存在实际的解决方案)会将一个元组发送到 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]
是对象内容。
在此之后要访问 class 变量,例如 poison
和 color
,您可以执行类似
if (b[1] == "Banana") {
var obj = b[2]: Banana;
writeln(obj.color);
}
和 class Apple
.