Adding dynamic properties to objects at runtime is a common requirement in many applications. A common approach to achieve this is to use a dictionary or collection of parameters. However, for scenarios where the number and names of properties are unknown beforehand, this approach falls short.
The .NET Framework provides a built-in solution for this problem: ExpandoObject. This class allows you to create dynamic objects to which you can add and remove properties at runtime.
// Create a dynamic object dynamic dynObject = new ExpandoObject(); // Add dynamic properties dynObject.SomeDynamicProperty = "Hello!"; // Execute dynamic actions dynObject.SomeDynamicAction = (msg) => { Console.WriteLine(msg); }; dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
For more complicated scenarios, you may want to create your own dynamic object that implements the DynamicObject class. This gives you more control over how dynamic member requests are handled.
public sealed class MyDynObject : DynamicObject { // Member dictionary private readonly Dictionary<string, object> _properties; public MyDynObject(Dictionary<string, object> properties) { _properties = properties; } // Get dynamic member names public override IEnumerable<string> GetDynamicMemberNames() { return _properties.Keys; } // Try to get a dynamic member 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; } } // Try to set a dynamic member public override bool TrySetMember(SetMemberBinder binder, object value) { if (_properties.ContainsKey(binder.Name)) { _properties[binder.Name] = value; return true; } else { return false; } } }
Using this approach, you can create dynamic objects with any desired properties:
var dyn = GetDynamicObject(new Dictionary<string, object>() { { "prop1", 12 } }); Console.WriteLine(dyn.prop1); dyn.prop1 = 150;
Caution: When using dynamic objects, be aware that the compiler will not be able to verify your dynamic calls, and you may encounter runtime errors or lack of intellisense support.
The above is the detailed content of How Can I Add C# Properties Dynamically at Runtime?. For more information, please follow other related articles on the PHP Chinese website!