如何定义一个方法 根据传进来的类型返回对应类型,如果数据库无则返回空。
以下是代码 null不能赋值给T 报错了 请问怎么改才能达到我的需求呢?
public T getEntity(string sqlString) where T : new()
{
DataTable dt = SqlHelper.GetDataTable(sqlString, CommandType.Text);
if (dt.Rows.Count > 0)
{
T t = new T();
return new T();
}
else {
return null;
}
}
return null 改成 return default(T); 如果T是值类型会返回0,如果是引用类型会返回null
能给详细点嘛 GetDataTable 的具体代码
//根据你的描述 我猜测应该是查数据库,然后返回实体的操作。
//如果这样的话需要用反射进行对象-属性赋值
///
/// 查询出一组数据
///
///
/// 存储过程名或sql语句
/// 指定是存储过程还是sql语句
/// 参数
/// 查询为空的时候返回 一个空集合(不是null)
public static List SelectList(string cmdText, CommandType comType, params SqlParameter[] param)
{
List list = new List();
using (SqlConnection conn = new SqlConnection(SystemConfig.GetConn()))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = conn;
com.CommandType = comType;
com.CommandText = cmdText;
com.Parameters.AddRange(param);
conn.Open();
using (SqlDataReader sr = com.ExecuteReader(CommandBehavior.CloseConnection))
{
while (sr.Read())
{
T obj = SetProperty(sr);
list.Add(obj);
}
}
}
}
return list;
}
///
/// 查询一个数据
///
///
/// 存储过程或sql语句
/// 指定是存储过程还是sql语句
/// 参数
/// 查询不到值得时候返回null
public static T SelectOne(string cmdText, CommandType comType, params SqlParameter[] param)
{
T obj = default(T);
using (SqlConnection conn = new SqlConnection("数据库连接字符串"))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = conn;
com.CommandType = comType;
com.CommandText = cmdText;
com.Parameters.AddRange(param);
conn.Open();
using (SqlDataReader sr = com.ExecuteReader(CommandBehavior.CloseConnection))
{
while (sr.Read())
{
obj = SetProperty(sr);
break;
}
}
}
}
return obj;
}
private static T SetProperty<T>(SqlDataReader sr)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < sr.FieldCount; i++)
{
string name = sr.GetName(i);
object objvalue = null;
try
{
objvalue = sr.GetValue(i);
}
catch (Exception e)
{
if (e.Message.Contains("DateTime"))
{
objvalue = new DateTime(2010, 1, 1, 00, 00, 01);
}
}
PropertyInfo property = properties.FirstOrDefault(new Func<PropertyInfo, bool>(item => string.Compare(name, item.Name, true) == 0));
if (property != null && objvalue != null && objvalue != DBNull.Value)
{
if (property.PropertyType == typeof(DateTime))
{
DateTime dt = new DateTime(2010, 1, 1, 00, 00, 01);
DateTime.TryParse(objvalue.ToString(), out dt);
objvalue = dt;
}
object onjd = objvalue;
if (onjd.GetType() == typeof(Int64) || onjd.GetType() == typeof(Int32) || onjd.GetType() == typeof(UInt32))
{
int in32 = int.Parse(onjd.ToString());
onjd = new int();
onjd = in32;
}
try
{
property.SetValue(obj, onjd, null);
}
catch (Exception ex)
{
throw ex;
}
continue;
}
}
return obj;
}