加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将泛型传递给扩展方法

发布时间:2020-12-15 23:41:24 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个通用的方法来执行一个查询,我可以传递存储的proc名称和参数(如果有的话). 执行查询后,结果存储在DataTable中 必须转换为List. DataTableToList() 是一种扩展方法,它将做同样的事情. 仅显示相关代码 呼叫者 var results= dh.ExecuteDataSet
我正在尝试创建一个通用的方法来执行一个查询,我可以传递存储的proc名称和参数(如果有的话).

执行查询后,结果存储在DataTable中
必须转换为List.

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;
            }
        }

问题是扩展方法调用给出了编译时错误

06003

那么对扩展方法进行哪些更改以使其接受泛型作为参数?

解决方法

这个程序:

public IEnumerable<T>  ExecuteDataSet<T>(
    string storedProcName,IConvertible> parameters = null)

还需要类型参数.

where T : class,new()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读