我将尝试构建一个通用的映射器,将SqlDataReader的结果转换为类对象。
以下是我的代码基本结构:
以下是我的代码基本结构:
public interface IObjectCore
{
//contains properties for each of my objects
}
public class ObjectMapper<T> where T : IObjectCore, new()
{
public List<T> MapReaderToObjectList(SqlDataReader reader)
{
var resultList = new List<T>();
while (reader.Read())
{
var item = new T();
Type t = item.GetType();
foreach (PropertyInfo property in t.GetProperties())
{
Type type = property.PropertyType;
string readerValue = string.Empty;
if (reader[property.Name] != DBNull.Value)
{
readerValue = reader[property.Name].ToString();
}
if (!string.IsNullOrEmpty(readerValue))
{
property.SetValue(property, readerValue.To(type), null);
}
}
}
return resultList;
}
}
public static class TypeCaster
{
public static object To(this string value, Type t)
{
return Convert.ChangeType(value, t);
}
}
大部分看起来都是可以工作的,但是一旦它试图设置属性的值,我就会收到以下错误:
对象不匹配目标类型
在我有 property.SetValue
的那行出现。
我已经尝试了所有方法,但我不知道可能出了什么问题。