Consider a scenario where you need to create a dynamic object with properties that can be added dynamically at runtime. Instead of using a dictionary or collection of parameters, you can leverage the ExpandoObject class.
ExpandoObject
ExpandoObject allows you to add and remove members of its instances at runtime, enabling dynamic binding capabilities. It provides a convenient way to manipulate properties dynamically, as seen in the following example:
dynamic dynObject = new ExpandoObject(); dynObject.SomeDynamicProperty = "Hello!";
Custom Dynamic Object
Building on the ExpandoObject approach, you can create a custom dynamic object that manages the retrieval and setting of dynamic properties. The following code demonstrates this concept:
public static dynamic GetDynamicObject(Dictionary<string, object> properties) { return new MyDynObject(properties); } public sealed class MyDynObject : DynamicObject { private readonly Dictionary<string, object> _properties; public MyDynObject(Dictionary<string, object> properties) { _properties = properties; } public override IEnumerable<string> GetDynamicMemberNames() { return _properties.Keys; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (_properties.ContainsKey(binder.Name)) { result = _properties[binder.Name]; return true; } else { result = null; return false; } } public override bool TrySetMember(SetMemberBinder binder, object value) { if (_properties.ContainsKey(binder.Name)) { _properties[binder.Name] = value; return true; } else { return false; } } }
By implementing the DynamicObject interface, you gain full control over the dynamic member access mechanism. This allows you to implement custom rules and behaviors for your dynamic object.
Usage
With your custom dynamic object in place, you can add properties and retrieve them at runtime:
var dyn = GetDynamicObject(new Dictionary<string, object> { { "prop1", 12 }, }); Console.WriteLine(dyn.prop1); dyn.prop1 = 150;
Note:
Dynamic objects are powerful but must be used with caution. The compiler cannot verify dynamic calls, and you may encounter runtime errors if you're not careful. It's crucial to understand the underlying mechanics and potential issues before using them in production code.
The above is the detailed content of How to Dynamically Add C# Properties at Runtime Without Using Collections?. For more information, please follow other related articles on the PHP Chinese website!