Create Object and its Properties at Run-time from

2019-07-02 11:57发布

问题:

I need to create dynamic object and its properties at run-time then create instance of this object to store values.

why I want above logic!

I am reading excel file in C# and first line of code is header which is actually properties and followed by each rows are record which is instance of dynamic object.

 List<string> ExcelDataHeader = new List<string>();
         for (int y = 2; y <= colCount; y++)
           {
             ExcelDataHeader.Add(xlRange.Cells[headerRow, y].Value2.ToString());
           }

  dynamic MyDynamic = new System.Dynamic.ExpandoObject();
    ??????????

I need to return excel read data in object

回答1:

You could use ExpandoObject here - it'll work, but you need to use the dictionary API:

IDictionary<string, object> obj = new ExpandoObject();
obj["id"] = 123;
obj["name"] = "Fred";

// this is the "dynamic" bit:
dynamic dyn = obj;
int id = dyn.id; // 123
string name = dyn.name; // "Fred"

However, I fail to see the point. Since you won't be referring to the object in C# code by things like obj.PropertyName, dynamic has very little purpose. You might as well just store each record in a Dictionary<string,object> or similar. Given what you describe, there are no places where you would actually use MyDynamic as a dynamic object.