enum constructors (creating members of members)

人走茶凉 提交于 2020-01-14 14:40:48

问题


In D, I'm trying to create an enum whose members have members. I can better explain what I'm trying to do with an example, where s and i stand in for the sub-members I'm trying to create:


In Python, I can do this:

class Foo(enum.Enum):
    A = "A string", 0
    B = "B string", 1
    C = "C string", 2

    def __init__(self, s, i):
        self.s = s
        self.i = i

print(Foo.A.s)

Java can do something like this:

public enum Foo {
    A("A string", 0),
    B("B string", 1),
    C("C string", 2);

    private final String s;
    private final int i;

    Foo(String s, int i) {
        this.s = s;
        this.i =i;
    }
}

How do I do this in D? I don't see anything in the official tutorial. If for whatever reason I can't do this in D, what's a good alternative?


回答1:


You can build an enum with any type, here we use a tuple (much like python) with a little alias for it to be easier to type.

import std.stdio;
import std.typecons;

alias FooT = Tuple!(string, "s", int, "i");
enum Foo : FooT {
    A = FooT("A string", 0),
    B = FooT("B string", 1),
    C = FooT("C string", 2),
}


void main(string[] args) {
    writeln(Foo.A.s);
}


来源:https://stackoverflow.com/questions/31766098/enum-constructors-creating-members-of-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!