gpt4 book ai didi

c# - List Count vs List null 条件,改变结果

转载 作者:行者123 更新时间:2023-11-30 19:40:16 26 4
gpt4 key购买 nike

我有一个程序,它首先遍历文件数据,然后将 (JSON) 数据转换为对象。对象取决于我试图从中访问数据的文件。这与我要问的问题几乎无关

当我完成项目并准备将其发送给我的 friend 时,我发现关于 List<> 有一点我不明白的 C#。

这是我使用的代码:

// File is not empty!
string file = File.ReadAllText(new MainWindow().getFileName("events"));
List<Event> events = JsonConvert.DeserializeObject<List<Event>>(file);

在此之后,我尝试填充 ListView通过我遇到的每个事件,或者我正在尝试填充 TextBlock有一条文字说,现在没有创建事件。

我正在使用这个条件。

if(events != null) {
// goes well
} else {
// populate the code text view
}

在此代码中,不会触发 else block 。如果有事件,它会填充列表,否则它会跳过 textView 更新代码。

enter image description here

但是,如果我改用这段代码,

if(events.Count != 0) {
// listview code..
} else {
// populate text view
}

使用它,我可以填充 textView,并且可以在页面中看到错误消息。

enter image description here

我已经添加了代码图像和工作示例。希望有人能告诉我区别

(List.Count == 0) || (List == null) 
/* irrelevant piece of code, I'm trying to ask, should I use
* List Count == 0 OR List is equal to null */

最佳答案

对于一些列表变量

List<SomeType> list = // initialization

变量 list 可能没有正确初始化并且没有设置对象。在这种情况下,变量的值为 null。虽然

  • list == null 评估为 true
  • list.Count 抛出一个 NullReferenceException

另一方面,如果可以获得列表。然后您将能够在列表上调用 Count,它会告诉您该列表中元素的数量。虽然

  • list == null 评估为 false
  • list.Count == 0 如果列表不包含任何元素,则计算结果为 true,如果列表至少包含一个元素,则计算结果为 false

为了安全起见(不仅仅是为了编程偏执狂),最好检查一个变量是否可以为空。我的意思是检查您从中获取对象的 API 的文档。

如果您知道它可能为空,则需要先检查 list == null 来解决这种情况。如果您不知道,您可能应该检查 null。我建议检查 null,如果是的话 - 为您的列表分配一个空列表。

List<SomeType> list = // initialization
list = (list == null) ? new List<SomeType>() : list;

if(list.Count == 0)
// do whatever you like here
else
// or even here

或者将初始化放入另一个专门用于检索列表的方法中。如果它以某种方式失败,它将返回一个空列表。这样您就可以通过仅检查一个条件来处理以下所有代码。 list.Count == 0 的条件。

List<SomeType> RetrieveList()
{
List<SomeType> list = // initialization possibly null
return (list == null) ? new List<SomeType>() : list;
}

希望对你有帮助

关于c# - List Count vs List null 条件,改变结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24331974/

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