我必须使用 if elseif elseif 检查 3 个条件。我怎样才能在 pharo 中做到这一点?我做了,但不确定,因为我在 pharo 中没有找到任何此类应用程序。
x = 25
ifTrue:[DoSomething]
ifFalse:[DoSomething else].
x < 25
ifTrue: [DoSomething]
ifFalse:[Domething else].
x > 25
ifTrue: [DoSomething ]
ifFalse:[DoSomething else].
最佳答案
您可以选择不同的设计(使用多态性、查找等),但这对于任何 OO 语言都几乎相同(特别是对于 Smalltalk,请参阅此 Refactoring if-chains in Smalltalk without class explosion )。
在 Smalltalk(以及其他语言,例如 Ruby)中,您有一个额外的选项,那就是类扩展。您可以设计自己的“if”语句来很好地匹配您的特定领域并使代码更加明显。
例如在您给定的示例中,我可以向 Number
类添加一个名为 compareTo:lesser:equal:greater:
的新方法,然后您的代码更改为
x compareTo: 25
lesser: [ do something ]
equals: [ do something else ]
greater: [ do something entirely different ]
这自然取决于您的特定领域,也许在不同的情况下措辞会有所不同。例如。对于集合,有 col ifEmpty: [ ] ifNotEmpty: [ ]
,对于 nil 有 ifNil:ifNotNil:
,用于检测 detect:ifFound:ifNone:
,对于字典 at:ifPresent:ifAbsent:
等
关于smalltalk - pharo中if elseif elseif怎么写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48442213/