在 Dlang 中使用反射在运行时获取变量值

Get the variable values at runtime using reflection in Dlang

是否可以在运行时将 dlang 中的 class/struct/other 变量值变为 get/set 其值?如果是,请提供示例。 以及是否可以获取运行时变量值?

例如:

class S{ int svariable = 5;}
class B { int bvariable = 10;}
void printValue(T, T instanceVariable, string variableName) {
    writeln("Value of ",  variableName, "=", instanceVariable.variableName);
}

输出:

Value of svariable = 5;
Value of bvariable = 10;

有一个名为 witchcraft 的库允许运行时反射。该页面上有如何使用它的示例。

我首先建议尝试像 @mitch_ 提到的反射库。但是,如果你不想使用外部库,你可以使用 getMember 来获取和设置字段以及调用函数:

struct S {
    int i;
    int fun(int val) { return val * 2; }
}

unittest {
    S s;
    __traits(getMember, s, "i") = 5; // set a field
    assert(__traits(getMember, s, "i") == 5); // get a field
    assert(__traits(getMember, s, "fun")(12) == 24); // call a method
}