从列表运行时创建对象及其属性 [英] Create Object and its Properties at Run-time from List
问题描述
我需要在运行时创建动态对象及其属性,然后创建此对象的实例来存储值。
为什么我想要超越逻辑! >
我在C#中读取excel文件,第一行代码是标题,其实际上是属性,后面是每行都是记录动态对象的实例。
列表< string> ExcelDataHeader = new List< string>(); (int y = 2; y< = colCount; y ++)
ExcelDataHeader.Add(xlRange.Cells [headerRow,y] .Value2.ToString());
}
动态MyDynamic = new System.Dynamic.ExpandoObject();
???
我需要在对象中返回excel读取数据
你可以使用 ExpandoObject
这里 - 它会工作,但你需要使用字典API:
IDictionary< string,object> obj = new ExpandoObject();
obj [id] = 123;
obj [name] =Fred;
//这是动态位:
dynamic dyn = obj;
int id = dyn.id; // 123
string name = dyn.name; //Fred
但是,我没有看到这一点。既然你不会被C#代码中的对象引用,例如 obj.PropertyName
, dynamic
目的。您也可以将每个记录存储在 Dictionary< string,object>
或类似文件中。鉴于您所描述的,没有实际使用 MyDynamic
作为动态
对象。
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
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.
这篇关于从列表运行时创建对象及其属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!