泛型参数类型约束

复制代码
 public class ModelHelper<T> where T : new() 
    {
        public static IList<T> DataTableToModel(DataTable dt)
        {

            IList<T> list = new List<T>();
            Type type = typeof(T); 
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertys)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pro.CanWrite) continue;
                        object value = Convert.ChangeType(dr[tempName], pro.PropertyType);
                        if (value != DBNull.Value)
                        {
                            pro.SetValue(t, value, null);                            
                        }
                        else {
                            pro.SetValue(t, "", null);
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }
    }
复制代码

public void Request<T>(List<T> EntityList)  where T : class{} 

这是参数类型约束,指定T必须是Class类型。 

.NET支持的类型参数约束有以下五种:

where T : struct                               | T必须是一个结构类型

where T : class                                | T必须是一个Class类型

where T : new()                               | T必须要有一个无参构造函数

where T : NameOfBaseClass          | T必须继承名为NameOfBaseClass的类

where T : NameOfInterface             | T必须实现名为NameOfInterface的接口

 class Core<T> where T : class, new()

where T:
泛型约束,约束类型T必须具有无参的构造函数
表示T必须是class类型或它的派生类。
new()构造函数约束允许开发人员实例化一个泛型类型的对象。 
一般情况下,无法创建一个泛型类型参数的实例。然而,new()约束改变了这种情况,要求类型参数必须提供一个无参数的构造函数。 
在使用new()约束时,可以通过调用该无参构造函数来创建对象。 
基本形式: where T : new() 

public interface IBaseDAL<T> where T : BaseModel, new()
{
  int Add(T model);
  int Update(T model);
  int Delete(T model);
}


让泛类 BaseDAL 实现 IBaseDAL 接口:
public class BaseDAL<T> : IBaseDAL<T> where T : BaseModel, new()

posted @   fengdong  阅读(226)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示