可以按名称更新 TRecord 成员
当您拥有记录成员的名称时,是否可以获取和设置 TMyRecord 的值?类似于RTTI
。
我无法使用数组,因为成员可能具有不同的数据类型。
type
TMyRecord = record
X: Integer;
Y: Integer;
Z: DateTime;
end;
var MyRecord: TMyRecord;
procedure UpdateValue(aRecordMemberName: string; AValue: Integer);
begin
MyRecord[aRecordmemberName] := AValue;
end;
function GetValue(aRecordMemberName: string): Integer;
begin
Result := MyRecord[aRecordmemberName];
end;
procedure Main();
begin
SetValue('X', 5);
showmessage( GetValue('Y').ToString );
end;
另外一点,是否可以迭代 Record
的所有成员,类似于迭代 TFields
或 TFieldDefs
?
谢谢。
- 在 Firemonkey 中使用 Delphi 11
Is it possible to have a get and set value for TMyRecord when you have the name of the record member? something similar to RTTI
.
I cannot use an array as the members may have different data types.
type
TMyRecord = record
X: Integer;
Y: Integer;
Z: DateTime;
end;
var MyRecord: TMyRecord;
procedure UpdateValue(aRecordMemberName: string; AValue: Integer);
begin
MyRecord[aRecordmemberName] := AValue;
end;
function GetValue(aRecordMemberName: string): Integer;
begin
Result := MyRecord[aRecordmemberName];
end;
procedure Main();
begin
SetValue('X', 5);
showmessage( GetValue('Y').ToString );
end;
On an additional note, is it possible to iterate through all members of a Record
, similar to iterating through TFields
or TFieldDefs
?
thanks.
- Using Delphi 11 in Firemonkey
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您有固定数量的不同类型的字段,则需要通过字符串名称访问这些字段会有点奇怪。不过,我们假设这是正确的做法。
RTTI 有点复杂(意味着您需要编写“很多”行代码)并且相当慢。当然,在你的情况下它可能足够快,所以它可能足够好。但这并不理想。
根据我的经验,人们往往过于渴望诉诸 RTTI。在大多数情况下,有更好的解决方案。
一种非 RTTI 解决方案是使用
TDictionary
。另一个是这样的:
where
然后你可以做这样的事情:
If you have a fixed number of fields of different types, it is somewhat strange that you need to access these by string names. Still, let's assume this is the right thing to do.
RTTI is a bit complicated (meaning that you need to write "many" lines of code) and rather slow. Sure, it will probably be fast enough in your case, so it will probably be good enough. But it isn't ideal.
In my experience, people are often too eager to resort to RTTI. In most cases, there are better solutions.
One non-RTTI solution would be to use a
TDictionary<string, Variant>
.Another would be like this:
where
Then you can do things like this: