关于泛型和反射

来源:百度知道 编辑:UC知道 时间:2024/05/24 10:53:07
关于泛型和反射
悬赏分:5 - 离问题结束还有 14 天 10 小时
先看我这个方法
public List<T> GetModelList<T>(T t,string path)
{
List<T> listt = new List<T>();
IEnumerable<XElement> xes = XDocument.Load(path).Element("r").Elements();
foreach (XElement xe in xes)
{
PropertyInfo[] pi = t.GetType().GetProperties();
foreach (PropertyInfo pinfo in pi)
{
pinfo.SetValue(t, xe.Attribute(pinfo.Name).Value, null);
}
listt.Add(t);
}
return listt;
}
作用是:把一个XML文件里面存储的数据转换成对象集合,当然每个xml都有一个对应的实体类。
现在的问题是:先看这个xml文件
<r>
<e id="a" ip="127.0.0.1:4244" attime="2009-10-31 18:42:02" />
<e id="b" ip="127.0.0.1:4269" attime="2009-10-31 1

这是因为你循环用的都是一个变量t

由于形参t只是用来取属性的,所以你应该在循环中每次都要再定义一个局部变量用于插入List<>

foreach (PropertyInfo pinfo in pi)
{
T ttt = new T();
pinfo.SetValue(ttt, xe.Attribute(pinfo.Name).Value, null);
}

listt.Add(ttt);

补充:

public List<T> GetModelList<T>(T t,string path) where T : new()