[英]How do I convert string array values to object in c#
我有以下數組:
"someData.childData.child1","someData.childData.child2", etc.
如何將此字符串數組轉換為對象。 也就是說,someData.childData.child1,someData.childData.child2,...都是對象。
您需要按如下方式使用Reflection
string[] yourArray = new string[] { "someData.childData.child1", "someData.childData.child2" };
System.Collections.Generic.List<dynamic> CreatedAll = new System.Collections.Generic.List<dynamic>();
for (int i = 0; i < yourArray.Length; i++)
{
string objStr = yourArray[i];
string[] objs = objStr.Split('.');
System.Collections.Generic.List<dynamic> created = new System.Collections.Generic.List<dynamic>();
for (int j = 0; j < objs.Length; i++)
{
var myObj = System.Activator.CreateInstance("namespaceName", objs[j]);
created.Add(myObj);
}
System.Reflection.PropertyInfo propertyInfo = created[1].GetType().GetProperty(objs[2]);
propertyInfo.SetValue(created[1], created[2], null);
System.Reflection.PropertyInfo propertyInfo1 = created[0].GetType().GetProperty(objs[1]);
propertyInfo1.SetValue(created[0], created[1], null);
CreatedAll.Add(created);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.