gpt4 book ai didi

c# - 检查 BsonValue 是否不为空

转载 作者:行者123 更新时间:2023-12-02 00:45:47 24 4
gpt4 key购买 nike

以以下来自 mongo 集合的摘录为例:

{"IsBasedOnProduct" : {
"CodeUV" : "09184",
"Name" : null,
"pricingVersion" : "B"
}
}

我想从此集合中提取 Name 字段并将其放入 C# 对象中。但我不知道如何管理 null 值。

这就是我在 C# 应用程序中所做的:

if (foo.Contains("IsBasedOnProduct"))
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") ? foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}

当然,当 Namenull 时,我会抛出一个 System.ArgumentNullException我该如何修复它以便在值为 null 时放置 string.Empty

最佳答案

使用以下代码快照修复它:

if (foo.Contains("IsBasedOnProduct") && foo["IsBasedOnProduct"].BsonType != BsonType.Null)
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name")&& foo["IsBasedOnProduct"]["Name"].BsonType != BsonType.Null ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}

关于c# - 检查 BsonValue 是否不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000276/

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