如何访问 class 或以字段名称作为字符串的记录字段?

How to access class or record field with the name of the field as a string?

假设您有记录或 class:

record R {
  var value: int;
}

如何使用字符串 "value" 访问字段 value

例如,在 Python 中,您可以使用 getattr 内置访问字段:

class C:
    def __init__(self, val):
        self.value = val

c = C(2)

print(getattr(c, 'value')) # prints 2

这在礼拜堂会是什么样子?

Reflection 模块的 getField()getFieldRef() 例程提供了这种能力。例如,下面的程序同时读取和写入字段 'value' (TIO):

use Reflection;

record R {
  var value: int;
}

var myR = new R(2);

writeln(getField(myR, "value"));  // print the field from 'myR' named "value"

getFieldRef(myR, "value") = 42;   // get a reference to the field from 'myR' named "value" and assign to it

writeln(myR);                     // print the resulting record