如何在 Chapel 中检查子类
How to check subclass in Chapel
这个可能真的很蠢。你如何在 Chapel 中检查对象的子类?
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");
// ?, kinda Java-ish, what should I do?
if (type(a) == Apple.class()) {
writeln("Go away doctor!");
}
虽然我问的是子类,但我意识到我也不知道如何检查它是否是 Fruit
class。
对于精确的类型匹配,您需要这样写:
if (a.type == Apple) {
writeln("Go away doctor!");
}
要检查 a
的类型是否是 Fruit
的子类型,这将起作用:
if (isSubtype(a.type, Fruit)) {
writeln("Apples are fruit!");
}
作为参考,有一个函数列表可以类似地用于检查类型信息here
*请注意,if
块中的括号不是必需的,因此您可以这样写:
if isSubtype(a.type, Fruit) {
writeln("Apples are fruit!");
}
前面的答案很好地解释了类型在编译时已知的情况,但如果它仅在 运行 时已知怎么办?
class Banana : Fruit {
var color: string;
}
class Apple: Fruit {
var poison: bool;
}
class Fruit {
}
var a:Fruit = new Apple(poison=true);
var b:Fruit = new Banana(color="green");
// Is a an Apple?
if a:Apple != nil {
writeln("Go away doctor!");
}
在这种情况下,a
到其潜在子类型 Apple
的动态转换会导致 nil
如果它实际上不是 Apple
或表达式编译时类型 Apple
如果是。
这个可能真的很蠢。你如何在 Chapel 中检查对象的子类?
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");
// ?, kinda Java-ish, what should I do?
if (type(a) == Apple.class()) {
writeln("Go away doctor!");
}
虽然我问的是子类,但我意识到我也不知道如何检查它是否是 Fruit
class。
对于精确的类型匹配,您需要这样写:
if (a.type == Apple) {
writeln("Go away doctor!");
}
要检查 a
的类型是否是 Fruit
的子类型,这将起作用:
if (isSubtype(a.type, Fruit)) {
writeln("Apples are fruit!");
}
作为参考,有一个函数列表可以类似地用于检查类型信息here
*请注意,if
块中的括号不是必需的,因此您可以这样写:
if isSubtype(a.type, Fruit) {
writeln("Apples are fruit!");
}
前面的答案很好地解释了类型在编译时已知的情况,但如果它仅在 运行 时已知怎么办?
class Banana : Fruit {
var color: string;
}
class Apple: Fruit {
var poison: bool;
}
class Fruit {
}
var a:Fruit = new Apple(poison=true);
var b:Fruit = new Banana(color="green");
// Is a an Apple?
if a:Apple != nil {
writeln("Go away doctor!");
}
在这种情况下,a
到其潜在子类型 Apple
的动态转换会导致 nil
如果它实际上不是 Apple
或表达式编译时类型 Apple
如果是。