我有一个函数:变量c获取类<T>在本例中的所有属性:
c ->
Id
Key
Value
public List<T> ReadStoreProceadure<T>(string storeName)
{
var result = new List<T>();
var instance = (T) Activator.CreateInstance(typeof (T), new object[] {});
var c = typeof (T);
var data = DataReader.ReadStoredProceadures(_factibilidad, storeName); // This part is returning verified data and it's ok
while (data.Read())
{
if (data.HasRows)
{
foreach (var item in c.GetProperties())
{
//item.SetValue(c, item.Name, null);
}
}
}
}如何将这些值添加到实例instance并将其添加到result变量中?有可能吗?
发布于 2015-01-26 17:40:01
我已经为IDataReader创建了一个扩展方法,它基本上完成了我认为您想要做的事情:
public static List<T> ToList<T>(this IDataReader dr) where T: new()
{
var col = new List<T>();
var type = typeof(T);
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
while (dr.Read())
{
var obj = new T();
for (int i = 0; i < dr.FieldCount; i++)
{
string fieldName = dr.GetName(i);
var prop = props.FirstOrDefault(x => x.Name.ToLower() == fieldName.ToLower());
if (prop != null)
{
if (dr[i] != DBNull.Value)
{
prop.SetValue(obj, dr[i], null);
}
}
}
col.Add(obj);
}
dr.Close();
return col;
}然而,你会注意到我选择了从相反的方向工作。我没有迭代类型的属性并从DataReader中获取它们,而是迭代DataReader列并检查类型上的匹配属性。您应该能够快速地修改它以适应您的数据检索方案。
https://stackoverflow.com/questions/28155333
复制相似问题