Vala中基于类的枚举?

时间:2019-11-08 16:08:26

标签: 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中尝试以下操作时,COMPRESSDECOMPRESS在从Action类外部访问时始终为 null。

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)

任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:2)

在Vala中,静态类成员是在class_init GObject函数期间初始化的,因此,只有在调用静态成员时,它们才可用。

最简单的解决方法是只创建一个实例。您可以立即将其丢弃,因为您所需要的只是副作用。