使用问号运算符C#在多个级别上检查NULL/空的null/空

发布于 2025-02-01 08:40:40 字数 388 浏览 3 评论 0原文

考虑一下我有以下类

class Dummy
{
    List<DummyObj> list;
}

class DummyObj
{
    string A;
    int B;
}

我有一个助手类,该类带有类型虚拟对象,并返回列表索引0处的当前值。我正在尝试处理所有空和空的案例(当假人通过时,当假人不是null,而是列表不是初始化的,当列表是初始化但空为空的

public string GetA(Dummy dummy)
{
    return dummy?.list?[0]?.A;
}

。 。

​一些错误的列表可以指出,请帮助我修复上述

语句:要澄清,我想返回上述任何条件。

Consider I have the following class

class Dummy
{
    List<DummyObj> list;
}

class DummyObj
{
    string A;
    int B;
}

I have a Helper Class which takes in an object of type Dummy and returns the value of A present at index 0 of list. I'm trying to handle all null and empty cases (when passed in dummy is null, when dummy is not null, but list is not initialized, when list is initialized but it's empty.

public string GetA(Dummy dummy)
{
    return dummy?.list?[0]?.A;
}

It works fine when dummy is null or list is null. But when list is empty, I get the following error - System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'

I'm definitely making some mistake handling empty list. Can someone please point it out and help me fix the above statement?

Edit: To clarify, I would like to return a null in case any of the above conditions hold true.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳絮泡泡 2025-02-08 08:40:40

使用以下内容:

return dummy?.list?.FirstOrDefault()?.A;

您应该避免在列表上使用索引,因为列表不是确定性的。如果您必须知道一个集合中项目的位置,请使用数组。

Use the following:

return dummy?.list?.FirstOrDefault()?.A;

You should avoid using index on a List as Lists aren't deterministic. If you have to know the position of an item in an a collection, use an array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文