属性设置器

时间:2017-09-19 07:45:07

标签: c# properties set nullreferenceexception

我有一个包含多个字符串字段的类。 此类表示序列化的模型,因此我必须检查其字段的长度。

我这样做

public String Address {
        get { return this.address; }
        set {
              if (value.Length > 15)
              {
                this.address= value.Substring(0,15);
              }
               else { this.address = value; }
            }
    }

所有以前的属性都已成功设置,但在某些时候我收到错误 '空引用异常'。

我会避免像

这样的解决方案
public String Address {
        get { return this.address; }
        set {
             if(value!=null){ 
             if (value.Length > 15)
              {
                this.address= value.Substring(0,15);
              }
               else { this.address = value; }
            }
          }
    }

你有什么建议?

0 个答案:

没有答案
相关问题