用于多种类型的实例 [英] instanceof use for multiple types
问题描述
我正在编写用于MiniJava的TypeChecker,ExpOp需要检查两个输入的表达式是否都是整数,以便使用正负号.
I am writing a TypeChecker for MiniJava and ExpOp needs to check if both of the entered expressions are of Integer to use plus, minus, times.
如何在包含两个表达式的if
语句内编写一行代码,并检查它们是否都是(instanceof
)Integer
的实例?
How can I write a line of code inside an if
statement that includes both expressions and checks if both of them are instances of (instanceof
) Integer
?
这就是我现在拥有的:
n.e1.accept(this) n.e2.accept(this) instanceof Integer
感谢您的帮助.
推荐答案
instanceof
是二进制运算符:它只能具有两个操作数.
instanceof
is a binary operator: it can only have two operands.
针对您的问题的最佳解决方案是Java的布尔AND运算符:&&
.
The best solution for your problem is Java's boolean AND operator: &&
.
它可用于评估两个布尔表达式:<boolean_exp1> && <boolean_exp2>
.
在且仅当在评估时两者均为true
时,才会返回true
.
It can be used to evaluate two boolean expressions: <boolean_exp1> && <boolean_exp2>
.
Will return true
if and only if both are true
at the time of the evaluation.
if (n.e1.accept(this) instanceof Integer &&
n.e2.accept(this) instanceof Integer) {
...
}
话虽这么说,另一种可能的解决方案是将它们都转换为try
/catch
块,并且当其中一个不是Integer
时将抛出ClassCastException
.
That being said, another possible solution is to cast them both inside a try
/catch
block, and when one of them is not an Integer
a ClassCastException
will be thrown.
try {
Integer i1 = (Integer) n.e1.accept(this);
Integer i2 = (Integer) n.e2.accept(this);
} catch (ClassCastException e) {
// code reached when one of them is not Integer
}
但是不建议这样做,因为它是称为按异常编程的已知反模式.
But this is not recommended as it is a known anti-pattern called Programming By Exception.
我们可以向您展示一千种方法(创建方法,创建类和使用多态性),但是没有任何一种方法比使用&&
运算符更好或更清晰 >.除此之外,其他任何事情都将使您的代码更加混乱和难以维护.你不想那样吗?
We can show you a thousand ways (creating methods, creating classes and using polymorphism) you can do that with one line, but none of them will be better or clearer than using the &&
operator. Anything other than that will make you code more confusing and less maintainable. You don't want that, do you?
这篇关于用于多种类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!