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

Reflection 如何在D中的编译时枚举结构或类中的名称和类型?,reflection,d,compile-time,Reflection,D,Compile Time,如何在编译时枚举结构或类中的名称和类型 i、 e.采取以下措施: struct Foo { int x; int y; } string serialise!(A)(A a) { ...magic... } auto f = Foo(1,2); serialise(f); -> "x:1, y:2" 谢谢 克里斯。像这样: foreach (index, field; myStruct.tupleof) { // field.stringof is "field"

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

i、 e.采取以下措施:

struct Foo {
  int x;
  int y;
}

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

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

克里斯。

像这样:

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);
}

实用示例:

您真的需要在编译时使用此枚举吗?因为从代码中我看到反射可以做你需要的事情。@Iaroslav你能给我举一个反射如何在D中使用的例子吗?是的,在编译时生成序列化函数(运行时)会更有效。对不起,我误读了标记。我的错