Dynamically add properties to a existing object

后端 未结 7 1327
说谎
说谎 2020-12-01 13:49

I create the person object like this.

 Person person=new Person(\"Sam\",\"Lewis\") 

It has properties like this.

person.Dob         


        
7条回答
  •  无人及你
    2020-12-01 14:11

    It's not possible with a "normal" object, but you can do it with an ExpandoObject and the dynamic keyword:

    dynamic person = new ExpandoObject();
    person.FirstName = "Sam";
    person.LastName = "Lewis";
    person.Age = 42;
    person.Foo = "Bar";
    ...
    

    If you try to assign a property that doesn't exist, it is added to the object. If you try to read a property that doesn't exist, it will raise an exception. So it's roughly the same behavior as a dictionary (and ExpandoObject actually implements IDictionary)

提交回复
热议问题