【发布时间】:2017-11-21 12:41:42
【问题描述】:
我正在尝试创建一个通用方法来执行查询,我可以在其中传递存储的过程名称和参数(如果有)。
执行查询后,结果存储在 DataTable 中 必须将其转换为列表。
DataTableToList()
是一个扩展方法,它会做同样的事情。
仅显示相关代码
来电者
var results= dh.ExecuteDataSet<EmployeeModel>("USP_GetEmployeeByID", new Dictionary<string, IConvertible>()
{
{"@ID", 1000}
});
DAL 代码
public IEnumerable<T> ExecuteDataSet<T>(string storedProcName, IDictionary<string, IConvertible> parameters = null)
{
var result = db.ExecuteDataSet(q);
DataTable dtResult = result.Tables[0];
var t = dtResult.DataTableToList<T>(); //Compile time error: The type T must be a reference type in order to use it as parameter
return t;
}
扩展方法
public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
List<T> list = new List<T>();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
问题是扩展方法调用给出编译时错误
The type T must be a reference type in order to use it as parameter compile time error.
那么要对扩展方法进行哪些更改以使其接受泛型作为参数?
【问题讨论】:
-
DataTableToList具有通用约束T:class但其他扩展方法没有该约束。这就是您看到此错误的原因。您也需要在那里应用相同的约束。
标签: c# .net generics parameters extension-methods