Convert class to dynamic and add properties

后端 未结 5 1836
庸人自扰
庸人自扰 2020-12-04 01:53

I have a class MyClass. I would like to convert this to a dynamic object so I can add a property.

This is what I had hoped for:

dynamic          


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 02:16

    You cannot add members to class instances on the fly.

    But you can use ExpandoObject. Use factory to create new one and initialize it with properties which you have in MyClass:

    public static ExpandoObject Create(int id)
    {
        dynamic obj = new ExpandoObject();
        obj.Id = id;
        obj.CreatedAt = DateTime.Now;
        // etc
        return obj;
    } 
    

    Then you can add new members:

    dynamic dto = Factory.Create(id);
    dto.newProperty = "123";
    

提交回复
热议问题