Delphi: One procedure to change all the fields of a record?
I have a record like this:
Tcustomer=record
Name: string;
IDNumber: Integer;
IsMarried: boolean;
end;
And I have a TCustomers_Manager
class that stores a list of all the customers. Is it possible to have a procedure like this:
Procedure ChangeCustomer(CustomerIndex: integer; field: string; value);
That sets the value for that specific field. For example:
ChangeCustomer(1, 'Name','John');
How can I implement this?
Update: To clarify, my question is basically in 2 parts:
1) How can I map开发者_如何学编程 the field name (in string) to the actual field in record?
2) Is it possible to pass a value that has different types? Or should I pass a single type and type cast it (like passing a string and then using strtoint()
)
I would use TClientDataSet.
- Create TClientDataSet with fields ID, Name, etc.
- Open Dataset, Fill with InsertRecord or Insert/Post
- Find Record with Locate
- Use FieldByName('FieldName').Value to access to or change data
Or you can take any MemoryDataSet component and use it in same way.
Second way is to convert record to class, declare Fields as published and use SetPropValue.
If you want to pass any Value you can use Variant. But you have to check types before assign.
You could, for example, do this (assuming lst: TList<TCustomer>
as you said in a comment):
Procedure ChangeCustomer(index: integer; i: byte; value: variant)
begin
case (i) of
0: lst[index].Name := value;
1: lst[index].IDNumber := value;
2: lst[index].IsMarried := value;
end;
end;
You could use a type (or enum) in place of i: byte
.
I dont't use Delphi from long time, so take my example as an idea, not like a Delphi app!!
精彩评论