因为每个表的结构都一样,所以我想用一个方法来读取多个表的数据放到实体,我想到用泛型可以实现,但是对泛型的使用又不熟悉,所以想问一下要实现这个功能要怎么改一下?
public T GetSTTableEntity<T>(string TableName,string Code)
        {
            string Strsql = "select * from " + TableName + " where CODE='" + Code + "' and IORDER > 0";
            try
            {
                T entity = new T();  //变量类型“T”没有new()约束,因此无法创建该类型的实例
                DataTable dt = DbHelperOra.Query(Strsql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["ID"] != null && dt.Rows[0]["ID"].ToString() != "")
                    {
                        entity.ID = decimal.Parse(dt.Rows[0]["ID"].ToString()); //“T”并不包含“ID”的定义
                    }
                    if (dt.Rows[0]["CODE"] != null && dt.Rows[0]["CODE"].ToString() != "")
                    {
                        entity.CODE = dt.Rows[0]["CODE"].ToString();//“T”并不包含……
                    }
                    if (dt.Rows[0]["VVALUE"] != null && dt.Rows[0]["VVALUE"].ToString() != "")
                    {
                        entity.VVALUE = dt.Rows[0]["VVALUE"].ToString();“T”并不包含……
                    }
                    if (dt.Rows[0]["IORDER"] != null && dt.Rows[0]["IORDER"].ToString() != "")
                    {
                        entity.IORDER = dt.Rows[0]["IORDER"].ToString();“T”并不包含……
                    }
                    return entity;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {                throw new Exception(ex.Message);
            }
        }

解决方案 »

  1.   

    定义一个接口如
    public interface I接口
            {
                public decimal ID { set; }
                public string CODE { set; }
                public string VVALUE { set; }
                public string IORDER { set; }
            }
    让这些实体继承这个接口,并定义一个无参构造函数(如果不存在有参构造可以不定义)
    public T GetSTTableEntity<T>(string TableName,string Code)
        where T : new(), I接口
      

  2.   

    定义一个公用实体commonModelcustomerModel
    自定义实体继承公用实体属性只能按一定规则或是索引配置这样才能满足你当前的需求
      

  3.   

    你在里面都是用DataTable,ColumnName都写死了,何必用泛型?
      

  4.   


    抛开你的设计合理与否不谈,单说范型,你可以看看范型有一种where in的应用,可以给范型本身作一个限定,令其具备“ID”的定义。
      

  5.   


    抱歉打错了。不是where in,而是where另外回复之后才发现2楼其实说的就是这个意思。抱歉我发重复了。看2楼即可。