• 这里有个坑---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()方法,只能使用”=“号来赋值。怪自己基础不牢。

  • 相关阅读:
    诊断Oracle 服从成绩
    联机热备份失踪败后,怎样翻开数据库?
    Oracle 8.0.4 for Windows NT的装配
    Oracle常用数据字典
    怎样快速查出Oracle数据库中的锁等待
    Oracle不凡包
    Developer/2000 R2.1 中文版 在 Windows NT 上的安置
    Oracle中巧用FORMS_DDL
    Oracle 基本常识
    autorun的执行的命令行
  • 原文地址:https://www.cnblogs.com/zuimengaitianya/p/5060577.html
Copyright © 2020-2023  润新知