【问题标题】:Overriding < in Pharo在 Pharo 中覆盖 <
【发布时间】:2015-12-12 13:22:06
【问题描述】:

我正在尝试覆盖 pharo 中的“

TimeCal 有以下变量:年月日时分。

我的想法是将所有变量转换为分钟,然后将它们与

"BlockClosure(Object)>>doesNotUnderstand: #>"

这是我的代码:

< comparand
| thisInMins comparandInMins |
thisInMins := [(year * 525600) + (month * 43829) + (day * 1440) + (hour * 60) + minute].
comparandInMins := [(comparand year * 525600) + (comparand month * 43829) + (comparand day * 1440) + (comparand hour * 60) + comparand minute].

(thisInMins > comparandInMins)
ifTrue: [true] ifFalse: [false]

以及我用来测试它的代码:

time1 := TimeCal new. 
time1 hour: 12.
time1 day: 12.
time1 month: 11.
time2 := TimeCal new. 
time2 hour: 12.
time2 day: 12.
time2 month: 8.
testing := time1 < time2.

我不确定我所做的是否正确。我找不到任何关于如何做到这一点的适当指南。

【问题讨论】:

  • thisInMinscomparandInMins 变量是块(BlockClosure 类型),不理解#。
  • 这就解释了!非常感谢,我不知道它们是 BlockClosure 类型的。
  • 它们属于BlockClosure 类型,因为您将它们包含在[] 中。删除那些方括号(就像 MartinW 所做的那样,请参阅他的答案),您将获得该块内内容的值。此外,您应该考虑在类端创建一个方法来在新实例上设置这些变量并返回实例,而不是手动设置每个小时/天/月的值。
  • 你知道 Timestamp 类吗?因为它的含义与您的 TimeCal 相同,但使用不同的表示形式并且已完全实现
  • @AmosM.Carpenter - 如果我删除了块,我会收到一个错误,它不理解 #*。

标签: overriding smalltalk pharo


【解决方案1】:

这个呢

< other
    year = other year ifFalse: [^year < other year].
    month = other month ifFalse: [^month < other month].
    day = other day ifFalse: [^day < other day].
    hour = other hour ifFalse: [^hour < other hour].
    ^minute < other minute

【讨论】:

  • 写得很好:小巧优雅
【解决方案2】:

如果您已正确初始化变量,这应该可以:

< comparand
| thisInMins comparandInMins |
thisInMins := (year * 525600) + (month * 43829) + (day * 1440) + (hour * 60) + minute.
comparandInMins := (comparand year * 525600) + (comparand month * 43829) + (comparand day * 1440) + (comparand hour * 60) + comparand minute.

^ thisInMins < comparandInMins

你为什么在你的分钟计算中加上方括号?

也看看这个:ifTrue: [true] ifFalse: [false]。如果某事为真则返回真,如果某事为假则返回假似乎是不必要的步骤。您可以直接返回分钟比较的结果。

【讨论】:

  • 我尝试了很多方法,看看能否让它发挥作用。感谢您的帮助!
  • 编辑:当我删除方括号时,它会给我一个 * 操作错误。但是它仍然不起作用,我得到了同样的错误。
  • 是不是说 MessageNotUnderstood: receiver of "*" is nil?这可能是因为您没有将变量初始化为零。添加一个initialize 方法并初始化您的变量。在 Pharo 中,initialize 在您创建一个类的新实例时被调用。
猜你喜欢
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2012-01-28
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
相关资源
最近更新 更多