.NET MVC Controller 注意事项

在大家使用Controller这个控制器的时候,经常会有一些行参,但是有些时候,如果使用不当,胡造成不必要的错误,如下面代码所示:

public ActionResult GetAllotRecordInfo(long id)
{
    var allotorderInfo = AllotRecordApp.Instance.GetOrderRebateInfo(new AllotRecordInput
    {
            ProposerSysNo = CurrentPromoter.SysNo,
            CurrentAllotSysNo = id
    });
    if (allotorderInfo != null)
    {
        return View(allotorderInfo);
    }

    return Error404("找不到此记录。。");
}

该代码传入一个为long的id,后面把id赋值给CurrentAllotSysNo,这个代码逻辑很简单,但是如果前台页面没有传入id这个值,那么在吧id赋值给CurrentAllotSysNo就会报错,如果

public ActionResult GetAllotRecordInfo(long id=0)
{
var allotorderInfo = AllotRecordApp.Instance.GetOrderRebateInfo(new AllotRecordInput
{
ProposerSysNo = CurrentPromoter.SysNo,
CurrentAllotSysNo = id
});
if (allotorderInfo != null)
{
return View(allotorderInfo);
}

return Error404("找不到此记录。。");

}
这样修改一下,把id给他赋值一下就不会报错,这是C#基本语言,基本类型在使用的时候必须初始化,当然也适用于下面这个情形

public ActionResult GetAllotRecordInfo(bool isMan=false)
{
    return Error404("找不到此记录。。");
}

所以大家在使用基本类型作为参数的时候必须要注意,养成良好的代码习惯很重要

猜你喜欢

转载自blog.csdn.net/Lvkaiwen/article/details/83410671