“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.”

介于这种情况,通常是:我们定义数据类型允许为null时,又用它进行赋值所导致的!如:
public int? Id { get; set; }
public decimal? Price { get; set; }

在这里插入图片描述

解决方案:
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;
}

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