Date dayMonthYearDo的正确参数是什么:在Smalltalk(Pharo / Squeak)中看起来像


Date dayMonthYearDo: aBlock 
"Supply integers for day, month and year to aBlock and return the result"
^ start dayMonthYearDo: aBlock

此消息的典型有效块应是什么样子?

在这种情况下,注释"提供整数等"意味着参数aBlock将接收三个整数作为"实际"参数:日数月份索引年份。这意味着您必须创建一个包含三个"正式"参数的块,例如,daymonthIndexyear,如下所示:

aDate dayMonthYearDo: [:day :monthIndex :year | <your code here>]

你在<your code here>里面编写的代码可以引用"形式"参数daymonthIndexyear,就好像它是一个带有这三个参数的方法一样。

这就是块在Smalltalk中通常的工作方式。

aDate
    dayMonthYearDo: [:day :monthIndex :year |
        monthIndex + day = 2
            ifTrue: [Transcript show: 'Happy ' , year asString, '!']]

更新

上面的例子通过"巧妙地"将monthIndex + day2进行比较来检查 1 月 1 日。事实上,由于两个变量都是>= 1,因此获得2的唯一方法是当daymonthIndex都是1时,即当接收方aDate是1月1日时。一个更"严肃"的方法看起来像

(monthIndex = 1 and: [day = 1]) ifTrue: [ <etc> ]

像这样:

Date today dayMonthYearDo: [:d :m :y| Transcript cr; 
        show: 'today is the ';
        show: d;
        show: 'th'
        ]
today is the 28th

但是,当然,您可能会做不同的事情,只是在成绩单上显示内容

最新更新