1
我可能會做一些錯誤語法或幾乎所以可選的回調「不這樣做」可能是有效的,但似乎這應該工作:與可選參數
class Thing {
//static dynamic noop =() { }; // fails
static dynamic noop = ([dynamic value]) { }; // works for null cases
dynamic _callback;
Thing._([dynamic callback([dynamic value])])
: this._callback = callback != null ? callback : Thing.noop;
factory Thing([dynamic callback([dynamic value])]) {
return new Thing._(callback);
}
}
當我運行這些測試時,第一一個失敗,但第二,第三和第四遍:
//Caught type '() => dynamic' is not a subtype of type '([dynamic]) => dynamic' of 'callback'.
test('callback with optional param',() {
var thing = new Thing(() { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param',() {
var thing = new Thing(([_]) { });
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param',() {
var thing = new Thing();
thing.doCallback();
thing.doCallback('data');
});
test('callback with optional param',() {
var thing = new Thing(null);
thing.doCallback();
thing.doCallback('data');
});
爲了跟進,我認爲這種方法將把Thing的簽名更改爲([動態回調(),動態數據(動態值)]),以便現有的消費者仍然可以按照平時註冊回調,但新消費者也可以選擇進入數據通知。 – Perry 2013-04-26 17:01:35