【发布时间】:2018-11-06 03:25:42
【问题描述】:
我正在使用 .NET Core 2.1.200 开发一个 ASP.NET Core MVC 应用程序。
我有一个响应模型和一个静态方法来从实体模型构建这个响应模型。
public static EntityTypeResponseModel FromEntityType(Entity.EntityType entityType)
{
return new EntityTypeResponseModel
{
Id = entityType.Id,
Name = entityType.Name,
// NullReferenceException
Fields = entityType.EntityTypeFields?.Select(x => FieldResponseModel.FromField(x.Field))
};
}
虽然我使用 null 传播,但会引发 NullReferenceException。
执行传统的 null 检查可以解决问题:
public static EntityTypeResponseModel FromEntityType(Entity.EntityType entityType)
{
var entityTypeResponseModel = new EntityTypeResponseModel
{
Id = entityType.Id,
Name = entityType.Name
};
if (entityType.EntityTypeFields != null)
{
entityTypeResponseModel.Fields =
entityType.EntityTypeFields?.Select(x => FieldResponseModel.FromField(x.Field));
}
return entityTypeResponseModel;
}
我错过了什么吗?这是一个错误吗?
【问题讨论】:
-
调试时究竟哪个引用为空?
-
检查
EntityTypeFields(集合)不是null并没有检查x(元素)也不是null。x.Field的类型是什么,.FromField方法有什么作用?
标签: c# nullreferenceexception c#-6.0 null-propagation-operator