简体   繁体   English

如果Jobject在C#中为空,如何使变量为空

[英]How to make the variable empty if the Jobject is empty in C#

I am getting a Null reference exception when the Jobject is empty.当 Jobject 为空时,我得到一个 Null 引用异常。

var subjects = item.SelectToken("$.subjects").ToObject<List<JObject>>()

I am want to set var subjects as empty when Jobject empty without throwing an error.我想在 Jobject 为空时将 var 主题设置为空而不会引发错误。

THanks谢谢

var subjects = item.SelectToken("$.subjects")?.ToObject<List<JObject>>() ?? new List<JObject>();

List<...>列表<...>

List is a collection and you need to define what's in the List. List 是一个集合,您需要定义 List 中的内容。 Like List<string> , List<object> , or, for your code, List<JObject> .List<string>List<object> ,或者,对于您的代码, List<JObject>

SelectToken("$.subjects")?. SelectToken("$.subjects")?.

This means that if SelectToken returns null, it stops there without doing .ToObject , and returns null .这意味着如果SelectToken返回 null,它会在不执行.ToObject的情况下停在那里,并返回null

The issue here is that SelectToken will return null when it can't find any object, and when you do .ToObject on a null you get a NullException .这里的问题是SelectToken将在找不到任何对象时返回 null ,而当您对null执行.ToObject时,您会得到NullException So one'd usually check if an object is null before further using its properties or functions.因此,在进一步使用它的属性或函数之前,通常会检查一个对象是否为空。

The question mark - Null-Conditional Operator ( Official documents ) is a quick syntactic sugar to achieve that, without having to write conditions like问号 - Null-Conditional Operator官方文档)是一种快速的语法糖来实现这一点,而无需编写类似的条件

if (... == null) 
{ ...convert to list... } 
else 
{ ...make empty list...}

?? ?? new List()新列表()

Not sure what you mean by empty , if you don't want null , but an empty List , Null-coalescing Operator might come to help.不知道你说的empty是什么意思,如果你不想要null ,但是一个空的ListNull-coalescing Operator可能会来帮忙。

It means that if the statement before ??意思是 if 之前的语句?? is null , returns the statement after ??null ,返回??之后的语句instead.反而。

For example, string a = b ?? c例如, string a = b ?? c string a = b ?? c means: string a = b ?? c表示:

string a = b != null ? b : c

But notice that a still can be null if c is null .但请注意,如果cnull ,则a仍然可以为null

It's also a syntactic sugar to help you avoid writing long statements for these checks are frequently needed.它也是一种语法糖,可帮助您避免为这些经常需要的检查编写长语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM