问题
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