【问题标题】:C# - Facing error in Collection model - Null Handling [duplicate]C# - 集合模型中面临错误 - 空处理[重复]
【发布时间】:2021-06-28 15:39:24
【问题描述】:

我有如下所示的方法,此方法在 C# 代码中的 for 循环内调用,如果 ProductLevelRecords 具有指定索引中的记录但如果给定索引中没有记录则会抛出错误,请让我知道如何解决此错误

private static bool HasRecords(CardFileModel CardFileModel, int index)
{
    if (CardFileModel?.ProductLevelRecords[index] != null) [this line gives error if no records in that index level]
    { 
        return !string.IsNullOrEmpty(CardFileModel?.ProductLevelRecords[index]?.OrderNumber.Trim());
    }

    return false;
}

异常消息 - “位置 1 没有行。”

我在这里遇到异常 - CardFileModel?.ProductLevelRecords[index] - 这是真的,在此集合的索引位置 1 中没有分配任何行。 那么如何避免这个错误信息 - 你能帮帮我吗

【问题讨论】:

  • 这能回答你的问题吗? Get value from array if not out of bounds
  • 这不是一个重复的问题,上面的链接是关于 LIST 我的不是列表对象 - 它的类模型
  • “上面的链接是关于 LIST mine is not list object” - 一个很好的例子,说明为什么在发布问题时应该始终确保提供正确的minimal reproducible example。也就是说,还有其他帖子与您的问题 重复。我已经更新了重复目标以适合您的面向数据库的方案。 (不过,坦率地说,之前的副本对于查看所使用的基本技术的人仍然有用,例如stackoverflow.com/a/30342302)。
  • 您可能需要在读取数据if (index < CardFileModel.ProductLevelRecords.Length)之前检查length来处理索引超出范围异常
  • 谢谢,我在课堂上看不到 Length/Count 属性 -

标签: c# .net


【解决方案1】:

您可以将[index] 替换为.ElementAtOrDefault(index)

编辑:

显然,ProductLevelRecords 不是 IEnumerable。 我知道它有一个索引器,并假设它有一个Length 属性。

试试下面的代码:

if (CardFileModel == null || index >= CardFileModel.ProductLevelRecords.Length)
    return false;

它可能被称为计数。

试试下面的代码:

if (CardFileModel == null || index >= CardFileModel.ProductLevelRecords.Count)
    return false;

编辑:

如果一切都失败了,您可以使用 try catch 块。

private static bool HasRecords(CardFileModel CardFileModel, int index)
{
    try
    {
        if (CardFileModel?.ProductLevelRecords[index] != null)
        { 
            return !string.IsNullOrEmpty(CardFileModel?.ProductLevelRecords[index]?.OrderNumber.Trim());
        }
    }
    catch
    {
        return false;
    }
}

【讨论】:

  • 嗨,感谢您的快速响应,我尝试了吹线 - CardFileModel?.ProductLevelRecords.ElementAtOrDefault(index) 它给出了一个错误 - 不包含“ElementAtOrDefault”的定义并且没有可访问的扩展方法可以找到接受“ProductLevelRecords”类型的第一个参数的“ElementAtOrDefault”
  • 基本上 CardFileModel 不是 List/IEnumerable ,这就是我没有获得该属性的原因,你能建议我有什么其他方法可以验证
  • 我在 CardFileModel.ProductLevelRecords 中没有看到“长度”选项 - 它给出的错误 - 不包含长度的定义。 - 你能推荐我吗
  • @Manas,CardFileModel是什么类型的?
  • 非常感谢先生,现在工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多