我正在使用动态类来生成列表,但是在属性中,我没有得到静态类中的名称,而是 [0]、1、[2] 等。我需要将这些名称放入属性中。
有人知道(可能)简单的答案吗?
这是我的代码
更新 1:
List<string> Properties = new List<string>();
Properties.Add("name");
Properties.Add("instituteTypeId");
Properties.Add("city");
Properties.Add("id");
List<DynamicClass> DynamicClassList = new List<DynamicClass>();
int i = 0;
foreach (DataRow r in _data.Rows)
{
DynamicClass dynamicClass = new DynamicClass();
foreach (String Property in Properties)
{
dynamicClass.property[Property.ToString()] = _data.Rows[i][Property].ToString(); // private string RandomString(int size)
}
DynamicClassList.Add(dynamicClass);
}
我的动态课程是:
public class DynamicClass
{
// property is a class that will create dynamic properties at runtime
private DynamicProperty _property = new DynamicProperty();
public DynamicProperty property
{
get { return _property; }
set { _property = value; }
}
}
public class DynamicProperty
{
// a Dictionary that hold all the dynamic property values
private Dictionary<string, object> properties = new Dictionary<string, object>();
// the property call to get any dynamic property in our Dictionary, or "" if none found.
public object this[string name]
{
get
{
if (properties.ContainsKey(name))
{
return properties[name];
}
return "";
}
set
{
properties[name] = value;
}
}
}
这应该给我相同的结果:
Medical data = new Medical();
data.Name = _data.Rows[i]["name"].ToString();
data.instituteTypeId = Convert.ToInt32(_data.Rows[i]["instituteTypeId"].ToString());
data.City = _data.Rows[i]["city"].ToString();
data.ID = Convert.ToInt32(_data.Rows[i]["id"].ToString());
list.Add(data);
更新 2:
public class Medical
{
public string Name { get; set; }
public int ID { get; set; }
public string City { get; set; }
public int instituteTypeId { get; set; }
}
如果我从 DynamicClassList 查看运行时的属性,我会看到动态(抱歉不知道如何上传图像)是这样的:
key value
[0] [{id,1}]
[1] [{name, Med 1}]
在静态类中,它确实根据我的需要正确
key value
[id] {1}
[name] {Med 1}
从我的角度来看,它们与幻灯片差异相同,静态我看到关键字段中的关键值和 [{key,value}] 中的动态
任何帮助将不胜感激