这里有个坑---entity为null的问题

       这里有个坑,最近加班赶个项目,忽然遇到个这个坑,先记录下来,纯当自己提高。---------每一个遇到的坑总结后都是一比财富。

       我们在做项目是会使用ajax返回结果,在返回结果的时候一般选择json数据格式。于是我们会选择一个统一的格式返回结果:如下定义entity。

       public class ErrorResult

      {
    public string errorCode { get; set; }
    public string errorMessage { get; set; }
   }

然后在外面在加一层方便控制。  

  public class CommJson
  {
    public string result { get; set; }
    public ErrorResult error { get; set; }
  }

当我们new一个CommJson对象时,我们总喜欢像下面那样写

CommJson commJson = new CommJson();

commJson.result="true";

commJson.error.errorCode="0";//这来是错误的写法

commJson.error.errorMessage="返回正确";

然后就返回序列化后的值 JsonHelper.Serialize(commJson);

这个写法在编译的时候是完全没有报错的,但是当我们允许到这来后,就会惊讶的发现commJson.error.errorCode="0";是不能赋值成功的。

最终后发现在我们new一个entity的时候他只会把当前的entity的字段自动设置为null,并没有实例化到下一层。即commJson.error=null。所以我们并不能为commJson.error.errorCode赋值,应为我们并没有实例化这个error对象。最终改为如下:

CommJson commJson = new CommJson();

ErrorResult error = new ErrorResult();

commJson.result="true";

error.errorCode="0";

error.errorMessage="返回正确";

commJson.error=error;

这样才可以。同事记住commJson.error.Add(error)也是错误的写法。原因都是commJson.error为null不能使用Add()方法,只能使用”=“号来赋值。怪自己基础不牢。

posted @ 2015-12-20 12:03  醉梦ai天涯  阅读(2535)  评论(4编辑  收藏  举报