【发布时间】: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 属性 -