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

前端 未结 7 1372
醉话见心
醉话见心 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:43
    dynamic MyDynamic = new System.Dynamic.ExpandoObject();
    MyDynamic.A = "A";
    MyDynamic.B = "B";
    MyDynamic.C = "C";
    MyDynamic.Number = 12;
    MyDynamic.MyMethod = new Func<int>(() => 
    { 
        return 55; 
    });
    Console.WriteLine(MyDynamic.MyMethod());
    

    Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.

    0 讨论(0)
  • 2020-12-04 08:44

    ExpandoObject is what are you looking for.

    dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
    MyDynamic.A = "A";
    MyDynamic.B = "B";
    MyDynamic.C = "C";
    MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;
    
    0 讨论(0)
  • 2020-12-04 08:44
    dynamic MyDynamic = new ExpandoObject();
    
    0 讨论(0)
  • 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<string> fields = new List<string>();
            // 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<String, Object>)exo).Add(field, field + "_data");
            }
    
            // output - from Json.Net NuGet package
            textBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exo);
    
    0 讨论(0)
  • 2020-12-04 08:59
     var data = new { studentId = 1, StudentName = "abc" };  
    

    Or value is present

      var data = new { studentId, StudentName };
    
    0 讨论(0)
  • 2020-12-04 09:05

    You can use ExpandoObject Class which is in System.Dynamic namespace.

    dynamic MyDynamic = new ExpandoObject();
    MyDynamic.A = "A";
    MyDynamic.B = "B";
    MyDynamic.C = "C";
    MyDynamic.SomeProperty = SomeValue
    MyDynamic.number = 10;
    MyDynamic.Increment = (Action)(() => { MyDynamic.number++; });
    

    More Info can be found at ExpandoObject MSDN

    0 讨论(0)
提交回复
热议问题