首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

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

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

C# code
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;        }

------------------------------------------------
C# code
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);        }

-------------------------------------------
C# code
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() 是没有必要的。甚至,其实反射也没有必要。我宁可手写一些代码,也不愿意使用反射。例如我会写
C# code
List<Message> result= QueryForList(sql, parameters, commandType, datarow=>  {      return new Message{ 创建时间= Datetime.Now,                          发件人= (string)datarow["发件人"],                          收件人= (string) datarow["收件人"],                          内容= (string)datarow["内容"]                        };  }) 

热点排行