枚举构造函数(创建成员的成员) [英] enum constructors (creating members of members)
本文介绍了枚举构造函数(创建成员的成员)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在D中,我试图创建一个枚举,其成员有成员。我可以更好地解释一下我想用一个例子,其中 s
和 i
- 我想创建:
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:
在Python中,我可以这样做:
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可以这样做:
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;
}
}
我如何在D中这样做?我在官方教程中没有看到任何东西。
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?
推荐答案
你可以用任何方法构建一个枚举类型,这里我们使用一个元组(很像python)和一个别名,它更容易输入。
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);
}
这篇关于枚举构造函数(创建成员的成员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文