Vala 中基于 Class 的枚举?

Class-based enums in Vala?

我想知道如何在 Vala 中创建基于 class 的枚举。

在 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 中尝试以下操作时,COMPRESSDECOMPRESSAction 外部访问 时总是 null class.

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 成员在 class_init GObject 函数期间初始化,因此在调用该函数之前它们不可用。

最简单的解决方法是只创建一个实例;你可以立即扔掉它,因为你所追求的只是副作用。