数据库查询的时分报错,“string”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法

数据库查询的时候报错,“string”必须是具有公共的无参数构造函数的非抽象类型,才能用作泛型类型或方法
本帖最后由 hjhxqxx 于 2012-05-20 07:57:01 编辑
代码:

public List<string> QueryAuthor(string strID)
        {
            string sql = "SELECT au_lname FROM authors WHERE au_id = @au_id";
 
            DbParameter param= dbUtility.CreateDbParameter("@au_id", strID);

            List<DbParameter> lstParam = new List<DbParameter>();

            lstParam.Add(param);

            List<string> result = new List<string>();

          result = dbUtility.QueryForList<string>(sql, lstParam, CommandType.Text);

            return result;
        }

------------------------------------------------------------------------------------

public List<T> QueryForList<T>(string sql, IList<DbParameter> parameters, CommandType commandType) where T : new()
        {
            DataTable data = ExecuteDataTable(sql, parameters, commandType);
            return EntityReader.GetEntities<T>(data);
        }

-------------------------------------------------------------------------------

public static List<T> GetEntities<T>(DataTable dataTable) where T : new()
        {
            if (dataTable == null)
            {
                throw new ArgumentNullException("dataTable");
            }
            //如果T的类型满足以下条件:字符串、ValueType或者是Nullable<ValueType>
            if (typeof(T) == typeof(string) || typeof(T) == typeof(byte[]) || typeof(T).IsValueType)
            {
                return GetSimpleEntities<T>(dataTable);
            }
            else
            {
                return GetComplexEntities<T>(dataTable);
            }
        }

-----------------------------------------------------------------------
在result = dbUtility.QueryForList<string>(sql, lstParam, CommandType.Text);这条语句报错。
这是什么原因呢?

------解决方案--------------------
你写的 new() 是没有必要的。甚至,其实反射也没有必要。我宁可手写一些代码,也不愿意使用反射。例如我会写
List<Message> result= QueryForList(sql, parameters, commandType, datarow=>
  {
      return new Message{ 创建时间= Datetime.Now,
                          发件人= (string)datarow["发件人"],
                          收件人= (string) datarow["收件人"],
                          内容= (string)datarow["内容"]
                        };
  })
假设我明知道你要反射来产生T的实力,那么我宁可自己写这样的回调代码来自己创建T的实例而不愿意使用反射。