问题
Is there any way that Vala supports Self Invoking? Either with a class, or with a method?
Javascript supports self invoking like below. Which is what im looking for.
(function(){
// some code…
})();
I'm attempting to load a class into a hashmap for dynamically loading.
回答1:
using Gee;
[CCode (has_target = false)]
delegate void MyDelegate();
int main() {
var map = new HashMap<string, MyDelegate>();
map["one"] = () => { stdout.printf("1\n"); };
map["two"] = () => { stdout.printf("2\n"); };
MyDelegate d = map["two"];
d();
return 0;
}
If you need a target in your delegate you have to write a wrapper, see this question: Gee HashMap containing methods as values
As you can see, you don't need self invokation. Self invokation would look something like this:
int main() {
(() => { stdout.printf("Hello world!\n"); })();
return 0;
}
This is not supported by Vala (I tested this with valac-0.22).
Invoking a delegate var works as expected:
delegate void MyDelegate();
int main() {
MyDelegate d = () => { stdout.printf("Hello world!\n"); };
d();
return 0;
}
来源:https://stackoverflow.com/questions/19495057/does-vala-support-self-invoking