工作中小知识点汇总(c#)

时间:2023-12-22 20:33:50

1、OOP 实体与数据库字段转换(注意 此时实体字段必须和数据库中查询的字段列名相同)

list = ModelExtend.GetByDataTablePart<EZRate>(ds.Tables[0]);
 /// <summary>
/// 实体和DataTable都有的数据才回给实体赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static List<T> GetByDataTablePart<T>(this DataTable data) where T : class, new()
{
if (data != null)
{
List<T> list = new List<T>(); foreach (DataRow row in data.Rows)
{
T t = row.GetByDataRowPart<T>();
if (t != null)
{
list.Add(t);
}
}
return list;
}
else
return null;
}
/// <summary>
/// 实体和DataRow都有的数据才回给实体赋值
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="data">数据</param>
/// <returns></returns>
public static T GetByDataRowPart<T>(this DataRow data) where T : class, new()
{
if (data != null)
{
T t = new T();
PropertyInfo[] properties = GetProperties(typeof(T)); foreach (PropertyInfo p in properties)
{
if (data.Table.Columns.Contains(p.Name))
{
object value = data[p.Name] == DBNull.Value ? p.PropertyType.Name.ToLower().Equals("string") ? string.Empty : null : data[p.Name];
p.SetValue(t, value, null);
}
}
return t;
}
else
return null; }

2、重载可以用这种方式,不用写两个方法

/// <summary>
/// 构造产品订单映射
/// </summary>
/// <param name="identify">产品订单标识</param>
/// <param name="supplier">供应商标识</param>
/// <param name="commodity">产品标识</param>
/// <param name="items">产品的具体项目(例如:机票)</param>
public CommodityOrderMapping(string identify, string supplier, string commodity, IEnumerable<string> items = null, String isEmergency="0")
{
this.Identify = identify;
this.Supplier = supplier;
this.Commodity = commodity;
this.IsEmergency = isEmergency;
if (items != null) this._Items.AddRange(items);
}
//订单映射
orderMap = new OrderMapping(eco.TOrderId, eco.PurchaseCode,
new CommodityOrderMapping[] { new CommodityOrderMapping(eco.FOrderId, eco.SupplierCode, "C1",items: sublist, isEmergency: IsEmagenrcy) });//子订单映射

在方法中赋默认值,例如 items ,isEmergency 在调用时 用 items:sublist isEmergency:IsEmagenrcy .也可以只写 items:sublist。

总结后边两个参数可写可不写,但是必须前面加上名称例如items:sublist 必须加items。