我有下一节课叫HIP
using System;
namespace Shared
{
public class HIP
{
public HIP ()
{
}
public double data_source { get; set; }
public string hid { get; set; }
public double wid { get; set; }
public double psn { get; set; }
}
}我得到了oData,并将每个属性添加到列表中,如下所示:
var client= new ODataClient(settings);
var packages =await client.For("HIP").FindEntriesAsync();
protected List<HIP> hcp = new List<HIP>();
foreach (var package in packages)
{
hcp.Add(new HIP {wid=Convert.ToSingle(package["wid"])});
hcp.Add(new HIP {hid=package["hid"].ToString()});
hcp.Add(new HIP {psn=Convert.ToSingle(package["psn"])});
hcp.Add(new HIP {data_source=Convert.ToSingle(package["data_source"])});
}我的问题是如何以最优/更好的方式进行预先操作。现在,我有了4-5个属性,我可以按以下方式键入每个属性名称:package["wid"]、package["hid"]、package["psn"]、package["data_source"];但是,如果我有几十个属性呢?我想知道有没有更好的迭代方法。
发布于 2015-05-05 21:51:26
您可以使用反射来执行以下操作:
var hcp = new List<HIP>();
var hipProperties = typeof(HIP).GetProperties();
hcp.AddRange(hipProperties.Select(prop =>
{
var hip = new HIP();
prop.SetValue(hip, Convert.ChangeType(package[prop.Name], prop.PropertyType), null);
return hip;
}).ToList();上面的代码将生成一个HIP对象的列表,每个对象上只设置一个属性。我相信您可能希望创建一个HIP对象,为每个包设置其所有属性,如下所示:
var client = new ODataClient(settings);
var packages = await client.For("HIP").FindEntriesAsync();
var hcp = new List<HIP>();
var properties = typeof(Hip).GetProperties();
foreach (var p in packages)
{
var hip = new HIP();
foreach (var prop in properties)
{
prop.SetValue(hip, Convert.ChangeType(p[prop.Name], prop.PropertyType), null);
}
hcp.Add(hip);
}https://stackoverflow.com/questions/30063817
复制相似问题