How do I set a class member value by its name in a string?

Benjamin Thaut code at benjamin-thaut.de
Wed Dec 27 20:43:45 UTC 2017


On Wednesday, 27 December 2017 at 20:04:29 UTC, Marc wrote:
> I'd like to set the members of a class by its name at runtime, 
> I would do something like this:
>
>> __traits(getMember, myClass, name) = value;
>
> but since name is only know at runtime, I can't use __traits(). 
> What's a workaround for this?

You will have to use a combination of compile time and runtime 
methologies.

Essentially what you want is this:

void setMemberValue(string name, int value)
{
   switch(name)
   {
     case "member1":
       member1 = value;
       break;
     case "member2":
       member2 = value;
       break:
     ...
   }
}

As you don't want to write this for all members by hand you 
should write a function which generates the source code for this 
switch using static foreach and __traits(allMembers) and then 
mixin the generated string into the setMemberValue method. If 
your members can have different types you will also need runtime 
type that can hold multiple types. For simplicity I just used 
"int" in the above example. You could use "std.variant" for this.


More information about the Digitalmars-d-learn mailing list