Adding members to a dynamic object at runtime

前端 未结 5 1099
无人共我
无人共我 2020-12-24 11:53

I am exploring the DynamicObject model in .NET 4.0. The application is one where an object will be described through some sort of text/xml file, and the program must create

5条回答
  •  借酒劲吻你
    2020-12-24 12:14

    Related to the Thanasis Ioannidis answer regarding a variant "If your base class derives from DynamicObject", there is a simpler way, just add method AddProperty in "MyClass" class like this:

        class MyClass: MyBaseClass
        {
            Dictionary dynamicProperties = new Dictionary();
    
            public void AddProperty(string key, object value){
                dynamicProperties[key] = value;
            }
    

    Then you can use

    dynamic myObject = new MyClass();
    myObject.AddProperty("DateOfBirth", new DateTime(1980,23,11));
    

    You don't need any override to "TryInvoke".

提交回复
热议问题