gpt4 book ai didi

c# - 我如何知道动态对象的属性是否不存在或其值为空?使用牛顿软件

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:12 27 4
gpt4 key购买 nike

如果我这样访问属性:

if (dynamicObject["propertyName"] == null)

我会在两种情况下为真:

  1. 此动态对象中不存在此属性。

  2. 该属性存在但其值为空

当我使用 Newtonsoft 库时,GetType() 将返回“JObject”,而“JObject”的 GetProperty() 不起作用(始终返回 null)。因此我无法使用它。

dynamicObject.GetType().GetProperty()

如何区分这两种情况?我可以做其他准确的检查吗?

最佳答案

有几种方法可以解决这个问题;两者非常相似。

选项 1

因为您已经知道您的动态对象实际上是一个 JObject,您可以转换它(或者完全消除动态变量并将您的 JSON 直接反序列化为 JObject从一开始)。从那里,您可以使用相同的语法来尝试获取属性值(JToken)。如果该属性不存在,则结果将为空。否则,您可以检查 token 的 Type 属性以确定它是 JTokenType.Null 还是其他 token 类型:

JObject jo = (JObject)dynamicObject;
JToken token = jo["propertyName"];
if (token == null)
{
Console.WriteLine("property does not exist.");
}
else if (token.Type == JTokenType.Null)
{
Console.WriteLine("property exists with a value of null.");
}
else
{
Console.WriteLine("property exists with with a value of \"" + token.ToString() + "\".");
}

fiddle :https://dotnetfiddle.net/3Nrwns

选项 2

如果您更喜欢按原样使用动态对象,则需要使用 object.ReferenceEquals 来确定该属性是否存在。如果是,那么您可以使用常规空检查来查明该值是否为空:

dynamic val = dynamicObject["propertyName"];
if (object.ReferenceEquals(val, null))
{
Console.WriteLine("property does not exist.");
}
else if (val == null)
{
Console.WriteLine("property exists with a value of null.");
}
else
{
Console.WriteLine("property exists with with a value of \"" + val.ToString() + "\".");
}

fiddle :https://dotnetfiddle.net/4Mmbak

关于c# - 我如何知道动态对象的属性是否不存在或其值为空?使用牛顿软件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466471/

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