C# 反射(Reflection)的用处分析

乱侃

       作为一名新手,一直没有勇气去写一篇分享。原因有很多:诸如:自己水平有限、语言表达不准确、写出的东西没有一点技术点被人嘲笑。今天在公司听了内部员工的一个分享,其中最重要的一点是:提升自身水平的最佳的途径就是——交流。不管你是通过什么途径,交流也好、整理成文字分享也好等等都是很好的方式。故此,今天献丑写一篇自己的心得分享,欢迎各路大神的指教!

   需求背景

     今天接到的需求里面有个这样的需求,如下图所示,需要打印出如Excel内容呈现的单据。

    动手操作第一版本

     而为了实现这个业务需要涉及三张表的数据。(存放单据的表、审核意见表、审核状态表)

     三张表的关系:单据表1:1审核状态表,单据表1:N审核意见表

     为了实现让View页面整洁,我定义了一个SpecialPrintModel类

public class SpecialPrintModel

{

/// <summary>

/// 供应商承担

/// </summary>

public string SupplierUnderTaker { get; set; }

/// <summary>

/// 客户订单号

/// </summary>

public string CustomerSerialNumber { get; set; }

/// <summary>

/// 付款金额

/// </summary>

public decimal PayAmount { get; set; }

/// <summary>

/// 开户行

/// </summary>

public string OpeningBank { get; set; }

/// <summary>

/// 收款单位

/// </summary>

public string CollectionMonad { get; set; }

/// <summary>

/// 银行帐号

/// </summary>

public string BankAccount { get; set; }

/// <summary>

/// 经办人

/// </summary>

public string ResponseiblePerson { get; set; }

/// <summary>

/// 分管领导

/// </summary>

public string Leader { get; set; }

/// <summary>

/// 财务审核

/// </summary>

public string FinanceApproval { get; set; }

/// <summary>

/// 财务经理审核

/// </summary>

public string FinanceManagerApproval { get; set; }

/// <summary>

/// 财务总监审核

/// </summary>

public string FinanceDirectorApproval { get; set; }

/// <summary>

/// CEO审核

/// </summary>

public string CEOApproval { get; set; }

/// <summary>

/// 流水号

/// </summary>

public string SerialNumber { get; set; }

}

public List<ShipSpecialPrintModel> GetTobePaidRecepit(ShipSpecialSearch search)

{

List<ShipSpecialPrintModel> curiseShipModel = new List<ShipSpecialPrintModel>();

var toBePaidModel = persistant.GetTobePaidRecepit(search);//查找出待支付的单据表信息

ArrayList serialArray=new ArrayList();//定义一个流水号列表

toBePaidModel.ForEach((u) => { serialArr.Add(u.SerialNumber); });

var toBePaidComment = persistant.GetTobePaidRecepitComment(serialArr);//查找出待支付单据的审核意见表(1个单据对应多少审核意见)

foreach (var item in toBePaidModel)

{

ShipSpecialPrintModel temp = new ShipSpecialPrintModel()

SupplierUnderTaker = supplierUnderTaker;

CustomerSerialNumber = item.CustomerOrderNumber;

PayAmount = item.PayAmount;

OpeningBank = item.PayBank;

CollectionMonad = item.Payee;

ResponseiblePerson = item.Creator;

SerialNumber = item.SerialNumber;

};

curiseShipModel.Add(temp);

foreach (var curise in curiseShipModel)

{

foreach (var comment in toBePaidComment)

{

if (comment.SerialNumber == curise.SerialNumber)

{

if (comment.ApprovalLevel == (int)LevelType.BranchedLeader)

{

curise.Leader = comment.Creator;

}

else if (comment.ApprovalLevel == (int)LevelType.Finance)

{

curise.FinanceApproval = comment.Creator;

}

else if (comment.ApprovalLevel == (int)LevelType.FinanceManager)

{

curise.FinanceManagerApproval = comment.Creator;

}

else if (comment.ApprovalLevel == (int)LevelType.ProjectDirector)

{

curise.FinanceDirectorApproval = comment.Creator;

}

else if (comment.ApprovalLevel == (int)LevelType.CEO)

{

curise.CEOApproval = comment.Creator;

}

}

}

}

return curiseShipModel

}

    呵呵,上面的代码基本完成了业务的需求,可是如果业务需要打印出CTO的名称、CIO的名称那在if else这边加,虽然很简单但是违背了开放-封闭的原则。故本人决定用反射去完成这if...else的事情。

因为if...else里面的判断是当前的这笔单据的审核意见表的层级是不是跟SpecialPrintModel的字段所对应的层级相等,若相等则在对应字段写入相对应的名称。决定把SpecialPrintModel这个类修改下。

 

   动手操作第二版本

public class ShipSpecialPrintModel

{

/// <summary>

/// 供应商承担

/// </summary>

public string SupplierUnderTaker { get; set; }

/// <summary>

/// 客户订单号

/// </summary>

public string CustomerSerialNumber { get; set; }

/// <summary>

/// 付款金额

/// </summary>

public decimal PayAmount { get; set; }

/// <summary>

/// 开户行

/// </summary>

public string OpeningBank { get; set; }

/// <summary>

/// 收款单位

/// </summary>

public string CollectionMonad { get; set; }

/// <summary>

/// 银行帐号

/// </summary>

public string BankAccount { get; set; }

/// <summary>

/// 经办人

/// </summary>

public string ResponseiblePerson { get; set; }

/// <summary>

/// 分管领导

/// </summary>

[LevelAttribute(Level = 1)]

public string Leader { get; set; }

/// <summary>

/// 财务审核

/// </summary>

[LevelAttribute(Level = 2)]

public string FinanceApproval { get; set; }

/// <summary>

/// 财务经理审核

/// </summary>

[LevelAttribute(Level = 3)]

public string FinanceManagerApproval { get; set; }

/// <summary>

/// 财务总监审核

/// </summary>

[LevelAttribute(Level = 4)]

public string FinanceDirectorApproval { get; set; }

/// <summary>

/// CEO审核

/// </summary>

[LevelAttribute(Level = 5)]

public string CEOApproval { get; set; }

/// <summary>

/// 流水号

/// </summary>

public string SerialNumber { get; set; }

}

public class LevelAttribute : Attribute

{

public int Level { get; set; }

}

var toBePaidComment = persistant.GetTobePaidRecepitComment(ArrayList.Adapter(toBePaidModel.Select(u => u.SerialNumber).ToList()));

var specialPropertyInfo = (from property in typeof(CuriseShipSpecialPrintModel).GetProperties()

where property.GetCustomAttributes(typeof(LevelAttribute), false).Count() > 0

select property).ToList();

toBePaidModel.ForEach((item)=>{

ShipSpecialPrintModel temp = new ShipSpecialPrintModel()

SupplierUnderTaker = supplierUnderTaker;

CustomerSerialNumber = item.CustomerOrderNumber;

PayAmount = item.PayAmount;

OpeningBank = item.PayBank;

CollectionMonad = item.Payee;

ResponseiblePerson = item.Creator;

SerialNumber = item.SerialNumber;

};

var thisComments=toBePaidComment.Where(u=>u.SerialNumber =item.SerialNumber ).ToList();

thisComment.ForEach((cm)=>

{

if(cm.ApprovalLevel==(specialPropertyInfo.GetCustomAttributes(typeof(LevelAttribute),false).First() as LevelAttribute).Level)

{

cm.SetValue(model,cm.Creator,null);

}

});

})

    然而看到,propertyInfos那边基本上每循环一次都需要去反射查找下元素,为了避免这样的性能消耗,决定再修改一翻,定义一个字典去存储SpecialPrintModel标有特性类的字段。

   动手操作第三版本

Dictionary<int, PropertyInfo> dic = new Dictionary<int, PropertyInfo>();

propertyInfos.ForEach((myProperty) => { dic.Add((a.GetCustomAttributes(typeof(LevelAttribute),false).First() as LevelAttribute).Level,myProperty));

} );

comments.ForEach((cm) =>

{

if (dic.Keys.Contains(cm.ApprovalLevel))

{

dic[cm.ApprovalLevel].SetValue(model, cm.Creator, null);

}

});

   总体经过三次的修改,已经避免if...else的代码。这样而言,也比较适合后面比如再需要打印CTO审核的名称。那样只需要再Model类里面填写字段与在字段上加上个特效。

  总结

      就像我同事说的那样,做任务事情只要想想、多敲几次。一些问题就不是问题了。好了,今天就写到这里吧。晚安各位!

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

以上是 C# 反射(Reflection)的用处分析 的全部内容, 来源链接: utcz.com/z/348660.html

回到顶部