是否可以從方法中將消息傳遞給類的實例?
這是我正在嘗試做的一個例子:
Define Class(
"example",
x=1;
test = Method( {name, method},
<< Insert(name, method);
);
);
t = New Object( example());
// This fails to insert the blah method
t:test("blah", Method({y}, show("Blah " || char(x) || char(y))));
t:blah(6);
//This succeeds in inserting and calling the blah method
t << Insert("blah", Method({y}, show("Blah " || char(x) || char(y))));
t:blah(6);我懷疑我可能需要明確地寫“this << Insert”,但這會產生不同的錯誤:
Define Class(
"example",
x=1;
test = Method( {name, method},
<STRONG>this << Insert(name, method);</STRONG>
);
);
t = New Object( example());
// This fails because "send expects scriptable object"
t:test("blah", Method({y}, show("Blah " || char(x) || char(y));));
t:blah(6);我還考慮過顯式調用 Send(無法添加方法)和 this:Send(無法解析名稱 Send)。
我還考慮過直接調用 this:Insert(無法解析名稱 Insert)和 Insert(成功添加了 blah 方法,但未能正確探測調用機制,因此沒有參數傳遞到方法中)。
動機:
我這樣做是因為我試圖為類屬性列表自動創建 getter 和 setter 方法。理想情況下,我將能夠做到以下幾點:
Define Class(
"example",
_init_ = Method( {assocArray},
For Each({property, updateMethod}, assocArray,
Insert(key, Eval Expr(Method({value}, TrySetProperty(Expr(property), value, Expr(updateMethod)))));
);
);
TrySetProperty=Method({parameter, value, expressionIfChanged},
match(value,
., ., //Do nothing if missing value
this << Get Value(parameter), ., //Do nothing if unchanged value
this << Insert(parameter, value); //Otherwise update the value
Eval(expressionIfChanged); //and eval the expression
);
);
);
properties = Associative Array({{"prop1", Expr(ThingToDoOnUpdate1)},{"prop2", Expr(ThingToDoOnUpdate2)}});
t = New Object( example(properties));