gpt4 book ai didi

c# - 使用空传播时出现 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:03 25 4
gpt4 key购买 nike

<分区>

我正在使用 .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;
}

我错过了什么吗?这是错误吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com