泛型返回处理

摘自圆子一个人,后面再研究

问题:

 

跟软谋公开课,讲了一个通用访问方法,三层结构, 通用访问数据库每一个表,只查询一条记录可行,多条记录时,无法使用泛型返回


private static string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

public List<T> QueryDomain<T>( )
{
string sqlwhere = "1=1";

Type type = typeof(T);
T ty = (T)Activator.CreateInstance(type);

string colunms=string.Join("," ,type.GetProperties().Select(p => string.Format("[{0}]",p.Name)));
string sql = string.Format("Select {0} from [{1}] where {2}", colunms,type.Name,sqlwhere);
using (SqlConnection conn2 = new SqlConnection(connString))
{
SqlCommand comand = new SqlCommand(sql, conn2);
conn2.Open();
SqlDataReader read = comand.ExecuteReader(CommandBehavior.CloseConnection);
if(read.Read())
{
foreach (var prop in type.GetProperties())
{
string propertyName = prop.Name;
prop.SetValue(ty, read[propertyName]);
}

}
}
return tList;(此处错误,应该是泛型返回值的问题,泛型函数无法返回泛型集合,应该用 TResult fun(TResult T)(T t) 制作;

}
}
}

 

 

/// <summary>
/// 根据指定单据获取此单据对应的账户利息结算记录(结息单的对应利息结算记录)
/// </summary>
/// <param name="i_PV">结息单据记录对象</param>
/// <returns>利息结算记录</returns>
public static IList<T> GetAccountBalance<T>(Investment_PrincipalVouch i_PV)
{
SqlParameter[] paras = new SqlParameter[2];
paras[0] = new SqlParameter("@VouchDate", DAHelper.ReadParam(i_PV.VouchDate));
paras[1] = new SqlParameter("@AccountID", DAHelper.ReadParam(i_PV.OutAccountID));
string strQuery = "SELECT * FROM dbo.KD_T_AccountBalance WHERE AccountID=@AccountID AND BalanceDate=@VouchDate";
SqlDataReader reader = DAHelper.ExecuteReader(strQuery, CommandType.Text, paras);

IList<T> list = new List<T>();
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();

while (reader.Read()) //读取传入的数据
{
T t = Activator.CreateInstance<T>(); //构造泛型实例

foreach (PropertyInfo propertity in properties) //遍历属性集合
{
try
{
object obj = reader[propertity.Name]; //从reader中获取列名等于属性名的值
if (obj.Equals(DBNull.Value)) //为空则设置属性为null
{
propertity.SetValue(t, null, null);
}
else //不为空
{
Type propertyType = propertity.PropertyType; //获取属性的类型
if (propertyType.IsGenericType) //如果此属性是泛型(这里判断原因是防止有类似int?的类型)
{
propertyType = propertyType.GetGenericArguments()[0];
}
propertity.SetValue(t, Convert.ChangeType(obj, propertyType), null); //设置属性值
}
}
catch (Exception ex) //抛出异常的原因是Model里的字段在数据库不存在,所以此异常不用捕获,直接跳过
{
}
}
list.Add(t); //将泛型对象加入到列表中去
}
return list;
}

转载于:https://www.cnblogs.com/plexus/p/6754399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值