[英]c# - check for null in a collection initializer
I am parsing a Json
document using Json.NET and creating an ArrayList
using a Collection Initializer
as follows 我正在使用Json.NET解析
Json
文档,并使用Collection Initializer
创建ArrayList
,如下所示
var array = new ArrayList
{
inputJson["abc"].ToString(),
inputJson["def"].Value<float>(),
inputJson["ghi"].Value<float>()
};
Now I would like to add a null check so it doesn't throw an exception if one of the properties is missing in the Json document. 现在,我想添加一个空检查,以便在Json文档中缺少其中一个属性的情况下不会引发异常。
Thanks 谢谢
Something like this would do the trick 这样的事情可以解决问题
var array = new ArrayList
{
inputJson["abc"] != null ? inputJson["abc"].ToString() : "",
inputJson["def"] != null ? inputJson["def"].Value<float>() : 0.0F,
inputJson["ghi"] != null ? inputJson["ghi"].Value<float>() : 0.0F
};
I would create extension methods to handle this. 我将创建扩展方法来处理此问题。 Note, I'm not positive on the types here, so bear with me:
注意,我对这里的类型不满意,所以请忍受:
public static string AsString(this JObjectValue jsonValue, string defaultValue = "")
{
if (jsonValue != null)
return jsonValue.ToString();
else
return defaultValue;
}
public static T As<T>(this JObjectValue jsonValue, T defaultValue = default(T))
{
if (jsonValue != null)
return jsonValue.Value<T>();
else
return defaultValue;
}
With usage: 用法:
var array = new ArrayList
{
inputJson["abc"].AsString(),
inputJson["def"].As<float>(),
inputJson["ghi"].As<float>(),
inputJson["jkl"].As(2.0f) //or with custom default values and type inference
};
This also has the benefit of avoiding hitting the indexer twice (once to check for null
, and a second time to convert the value), and avoids repeating yourself as to how you parse/read the json input. 这还具有避免两次击中索引器的好处(一次检查
null
,第二次转换该值),并且避免重复解析或读取json输入的方式。
You can try this : 您可以尝试以下方法:
var array = new ArrayList
{
inputJson["abc"] ?? inputJson["abc"].ToString(),
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.