How to create own dynamic type or dynamic object in C#?

前端 未结 7 1399
醉话见心
醉话见心 2020-12-04 08:05

There, is for example, ViewBag property of ControllerBase class and we can dynamically get/set values and add any number of additional fields or properties to t

7条回答
  •  抹茶落季
    2020-12-04 08:47

    I recently had a need to take this one step further, which was to make the property additions in the dynamic object, dynamic themselves, based on user defined entries. The examples here, and from Microsoft's ExpandoObject documentation, do not specifically address adding properties dynamically, but, can be surmised from how you enumerate and delete properties. Anyhow, I thought this might be helpful to someone. Here is an extremely simplified version of how to add truly dynamic properties to an ExpandoObject (ignoring keyword and other handling):

            // my pretend dataset
            List fields = new List();
            // my 'columns'
            fields.Add("this_thing");
            fields.Add("that_thing");
            fields.Add("the_other");
    
            dynamic exo = new System.Dynamic.ExpandoObject();
    
            foreach (string field in fields)
            {
                ((IDictionary)exo).Add(field, field + "_data");
            }
    
            // output - from Json.Net NuGet package
            textBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exo);
    

提交回复
热议问题