简体   繁体   English

从列表运行时创建对象及其属性

[英]Create Object and its Properties at Run-time from List

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. 我在C#中读取excel文件,第一行代码是标题,它实际上是属性,后面跟着每一行都是记录,它是动态对象的实例。

 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 我需要在对象中返回excel读取数据

You could use ExpandoObject here - it'll work, but you need to use the dictionary API: 可以在这里使用ExpandoObject - 它可以工作,但你需要使用字典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. 由于您不会通过obj.PropertyName类的东西在C#代码中引用该对象,因此dynamic用途很少。 You might as well just store each record in a Dictionary<string,object> or similar. 您也可以将每个记录存储在Dictionary<string,object>或类似的中。 Given what you describe , there are no places where you would actually use MyDynamic as a dynamic object. 根据您描述的内容 ,您无法将MyDynamic实际用作dynamic对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM