你永远不会得到一个空JToken
.正如this post所说,Newtonsoft JSON被设计为不允许任何null值.每个null值都被转换为Null
类型的JValue
实例.
为了更有说服力,看看GetEnumerator
在source code中是如何实施的:
public IEnumerator<KeyValuePair<string, JToken?>> GetEnumerator()
{
foreach (JProperty property in _properties)
{
yield return new KeyValuePair<string, JToken?>(property.Name, property.Value);
}
}
JProperty.Value
的类型是JToken
,而不是JToken?
.
我怀疑它实现IDictionary<string, JToken?>
而不是IDictionary<string, JToken>
的原因是因为索引器被设计为在找不到键时返回NULL,并且也接受NULL值.
var token = someJObject["key"];
// unlike a Dictionary<TKey, TValue>,
// token is null if "key" is not a key in the JSON object,
// instead of throwing an exception
// you can also set a particular key as null directly, instead of making a JValue representing "null"
someJObject["key"] = null;
IDictionary<string, JToken>
要求索引器是不可空的JToken
类型,因此它无法实现.