Add a variable to a class instance at runtime: Difference between revisions
Add a variable to a class instance at runtime (view source)
Revision as of 17:02, 16 May 2024
, 17 days agoPascalABC.NET
m (→{{header|Wren}}: Changed to Wren S/H) |
(PascalABC.NET) |
||
Line 1,472:
01.06.1993
</pre>
=={{header|PascalABC.NET}}==
Adding variables to an object at runtime is not possible in PascalABC.NET because it is a statically typed language requiring the names of all class variables to be known at compile time.
However, we can make it appear as though variables are being added at runtime by using a Dictionary.
<syntaxhighlight lang="delphi">
type
MyClass = class
private
dict := new Dictionary<string,object>;
public
procedure Add(name: string; value: object) := dict[name] := value;
property Items[name: string]: object read dict[name]; default;
end;
begin
var obj := new MyClass;
obj.Add('Name','PascalABC.NET');
obj.Add('Age',16);
Println(obj['Name'],obj['Age']);
var obj1 := new MyClass;
obj1.Add('X',2.3);
obj1.Add('Y',3.8);
Println(obj1['X'],obj1['Y']);
end.
</syntaxhighlight>
{{ out }}
<pre>
PascalABC.NET 16
2.3 3.8
</pre>
=={{header|Perl}}==
|