Cod*_*ger 3 .net c# generics parameters extension-methods
我正在尝试创建一个通用的方法来执行一个查询,我可以传递存储的proc名称和参数(如果有的话).
执行查询后,结果存储在DataTable中,该DataTable必须转换为List.
DataTableToList()
是一种扩展方法,它将做同样的事情.
仅显示相关代码
呼叫者
var results= dh.ExecuteDataSet<EmployeeModel>("USP_GetEmployeeByID", new Dictionary<string, IConvertible>()
{
{"@ID", 1000}
});
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
扩展方法
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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是扩展方法调用给出了编译时错误
Run Code Online (Sandbox Code Playgroud)The type T must be a reference type in order to use it as parameter compile time error.
那么对扩展方法进行哪些更改以使其接受泛型作为参数?
这个程序:
public IEnumerable<T> ExecuteDataSet<T>(
string storedProcName,
IDictionary<string, IConvertible> parameters = null)
Run Code Online (Sandbox Code Playgroud)
还需要类型参数.
where T : class, new()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
551 次 |
| 最近记录: |