搜索
您的当前位置:首页正文

“Nullable object must have a value.” :“Object reference not set to an instance of an object.”

来源:好走旅游网

1.System.InvalidOperationException:“Nullable object must have a value.”

解决方案:
1.在进行赋值之前确保,赋值对象已经存在值,即:非null
2.若无法确保是否存在值,给予一个默认值,即可;

2.System.NullReferenceException:“Object reference not set to an instance of an object.”

而这种情况,通常则是:我们查询数据的时候,返回的对象为null,其属性值,如:IDNO…,我们需要使用其属性值导致的!

解决方案
1.三元表达式
2.简单封装复用

//三元表达式
var product = GetAll().Where(a => a.No == "FYCJ0001").FirstOrDefault() == null
    ? null : GetAll().Where(a => a.No == "FYCJ0001").FirstOrDefault();
string name = product == null ? null : product.Name;
static void Main(string[] args)
{
     //封装处理
     Product product = GetAll().Where(a => a.No == "FYCJ0001").FirstOrDefault();
     string name = (string)Convert(product, "Name");
     Console.WriteLine("name:" + name);
     Console.ReadKey();
}
static object Convert<T>(T t, string property)
{
      return t == null ? null : GetValue(t, property);
}
static object GetValue<T>(T t, string property)
{
      var value = t.GetType().GetProperty(property).GetValue(t);
      return value == null ? null : value;
}

其实,如果没必要,应当尽量规避这些用法才是上策!

因篇幅问题不能全部显示,请点此查看更多更全内容

Top