如何在D中编译时枚举结构或类中的名称和类型?

时间:2011-09-21 08:10:33

标签: reflection d compile-time

如何在编译时枚举结构或类中的名称和类型?

即。做以下事情:

struct Foo {
  int x;
  int y;
}

string serialise!(A)(A a) {
  ...magic...
}

auto f = Foo(1,2);
serialise(f); -> "x:1, y:2"

谢谢,

克里斯。

1 个答案:

答案 0 :(得分:8)

像这样:

foreach (index, field; myStruct.tupleof)
{
    // field.stringof is "field", slice is to cut off "myStruct."
    pragma(msg, "Name: " ~ myStruct.tupleof[index].stringof[9..$]);
    pragma(msg, "Type: " ~ typeof(field).stringof);
}

实际例子:https://github.com/CyberShadow/ae/blob/master/utils/json.d#L107