ASP.NET 视图中的 MVC 模型 (ViewModel) 三元运算符空值检查

ASP.NET MVC Model in View (ViewModel) ternary operator null check

我知道可以使用三元运算符(“?”)检查值是否为空,如果不为空则继续"chained methods let's call it"。示例:Model?.FirstOrDefault(); 为什么这行不通?我想说"if the Model is not empty call the FirstOrDefault method, else don't do anything"。收到此错误

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Linq.Enumerable.FirstOrDefault(...) returned null.

通常我用过?用于将 API 数据提取的访问器设置为 ?意味着该值可以为空。我认为这更符合您的需求:

if (String.IsNullOrEmpty(TableName.AttributeName))
 {
   FirstOrDefault();
 }

你不能这样做,因为 FirstOrDefault() 是一个 Extension Method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

解决方法是不使用 Null Conditional Operator 这只是语法糖。

string myVariable;

if (Model != null)
    myVariable = Model.FirstOrDefault();