版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xsh096011/article/details/81627383
泛型
List:表,一览表;明细表;在编程语言中List是类库中的一个类;List的特色是在集合的任何位置增加或删除元素都很快,但是不支持随机存取;List是类库提供的众多容器之一;List以模板方式实现(即泛型),可以处理任意类型的变量;
优点:
1. 编写B层的人员无需手动填写需要的字段,直接按一下点,全都提示出来了,想用哪个用哪个,不会出现写错的情况;
2. 不必了解数据库结构;
3. 符合面向对象思想;
4. 实体类的属性是强类型,每个字段的类型都是已知的;
举一个泛型的例子:
IDAL层:
/// <summary>
/// 用户的登录
/// </summary>
/// <param name="UserInfo"></param>
/// <returns></returns>
List<UserInfo> LoginUser(UserInfo UserInfo);
D层:
/// <summary>
/// 用户登陆
/// </summary>
/// <param name="UserInfo">UserInfo实体</param>
/// <returns></returns>
public List<UserInfo> LoginUser(UserInfo UserInfo)
{
SqlParameter[] SqlParams = {new SqlParameter("@CardNo",UserInfo.CardNo),
new SqlParameter("@Pwd",UserInfo.Pwd)};
string sql = "select * from t_user where CardNo=@CardNo and Pwd=@Pwd ";
DataTable table = sqlhelper.ExecuteQuery(sql, SqlParams, CommandType.Text);
ConverHelper converHelper = new ConverHelper();
List<UserInfo> list = new List<UserInfo>();
return converHelper.convertToList<UserInfo>(table);
}
DataTable 转泛型:(D层下面封装一个ConverHelper类)
using System.Data;
using System.Collections;
using System.Reflection;
namespace DAL
{
public class ConverHelper
{
public List<T> convertToList<T>(DataTable dt)where T:new()
{
//定义集合
List<T> ts = new List<T>();
//获得此模型类型
Type type = typeof(T);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach(DataRow dr in dt.Rows)
{
T t = new T();
//获得此类模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach(PropertyInfo pi in propertys)
{
//将属性名称赋值给临时变量
tempName = pi.Name;
//检查DataTable是否包含此列(列名==对象的属性名)
if(dt.Columns.Contains(tempName))
{
//判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}
}
Try-Catch
为什么要用Try-Catch?
如上图所示,我们写的程序不可能一点错也没有,而我们不想把错误展示给用户看;Try-Catch可以帮助我们解决这个问题;
trycatch finally的用法:
try
你想要写的程序
catch
捕获你想写的程序里面所有发生的异常
finally
无论发生还是不发生异常,你都想执行的代码
因此我的代码是这么写的:
U层
try
{
flag = facade.SelectUser(user);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
B层
if (list.Count >0 )
{
flag = false;
throw new Exception("密码或用户名错误!");
}
else
{
flag = true;
throw new Exception("密码或用户名错误!");
}
本来应该是上面的报错情况,经过Try-Catch处理后:
目前只是一个简单的了解,先做下总结;