小编Cod*_*ger的帖子

将泛型传递给扩展方法

我正在尝试创建一个通用的方法来执行一个查询,我可以传递存储的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>(); …
Run Code Online (Sandbox Code Playgroud)

.net c# generics parameters extension-methods

3
推荐指数
1
解决办法
551
查看次数

标签 统计

.net ×1

c# ×1

extension-methods ×1

generics ×1

parameters ×1