vala - Vala 中基于类的枚举?
问题描述
我想知道如何在 Vala 中创建基于类的枚举。
在 Java 中,您可以执行以下操作:
public class Main {
public static void main(String[] args) {
Action action = Action.COMPRESS;
System.out.printf("Action name: %s, index %d", action.getName(), action.getIndex());
}
}
class Action {
public static final Action COMPRESS = new Action("Compress", 60);
public static final Action DECOMPRESS = new Action("Decompress", 70);
private String name;
private int index;
private Action(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
}
但是当我在 Vala 中尝试以下操作时COMPRESS
,从课堂外访问时DECOMPRESS
总是为空。Action
public static int main(string[] args) {
stderr.printf("Action name: %s\n", UC.Action.COMPRESS.get_name());
}
public class UC.Action : GLib.Object {
public static UC.Action COMPRESS = new UC.Action("Compress");
public static UC.Action DECOMPRESS = new UC.Action("Decompress");
private string name;
[CCode (construct_function = null)]
private Action(string name) {
this.name = name;
}
public string get_name() {
return name;
}
}
该代码输出以下内容:Performing (null)
.
任何想法如何做到这一点?
解决方案
在 Vala 中,静态类成员在class_init
GObject 函数期间被初始化,因此在调用之前它们不可用。
最简单的解决方法是只创建一个实例;您可以立即将其丢弃,因为您所追求的只是副作用。
推荐阅读
- v8 - 尝试更新库时无法找到“v8_base”
- python - 决策树图不起作用 python 3.6 不保存
- java - 在 JPanel 中对齐 JTextField、JLabels 和 JButton
- css - 如何在 CSS 中强制使用相同数量的文本?
- html - 每个浏览器的背景图都不一样,哪个是正确的?
- angular - HttpInterceptor 不适用于延迟加载的模块
- json - 在 spark scala 中删除 json 解析中的重复属性
- python - Chromedriver/Selenium 问题
- java - 使用 .endsWith() 语句进行条件检查
- spring - 使用 Spring Data JPA 获取时双向 OneToMany 关系中的重复实体