gpt4 book ai didi

c# - 非特例,数组越界

转载 作者:行者123 更新时间:2023-12-03 19:11:07 28 4
gpt4 key购买 nike

我知道我正在尝试做的是一些 hack,但它仍然很有趣。

我所处的情况很可能是一个数组可能没有我预期的那么多项目。

这是概念:

namespace TESTAPP
{
class Program
{
static void Main(string[] args)
{
string derp = "foooooo";
//The split is important, you might not have the character there to split by
Writer(derp.Split('x')[0] ?? ".");
Writer(derp.Split('x')[1] ?? ".");
}

private static void Writer(string writeme)
{
Console.WriteLine(writeme ?? "..");
}
}
}

执行上述打印时,我自然不会太惊讶:

foooooo

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at TESTAPP.Program.Main(String[] args) in [snip]\TESTAPP\Program.cs:line 15

我应该如何从逻辑上处理这种情况? try/catch block 似乎有些矫枉过正。

最佳答案

首先,您只想拆分一次,而不是对每个部分再次拆分:

string derp = "foooooo";
string[] parts = derp.Split('x');
// parts == { "foooooo" }
// parts.Length == 1

现在您有一个包含多个部分的数组,因此您可以在访问每个部分之前简单地检查 Length 属性:

Writer(parts.Length > 0 ? parts[0] : ".");
Writer(parts.Length > 1 ? parts[1] : ".");
Writer(parts.Length > 2 ? parts[2] : ".");
Writer(parts.Length > 3 ? parts[3] : ".");
Writer(parts.Length > 4 ? parts[4] : ".");

for (int i = 0; i < 5; i++)
{
Writer(parts.Length > i ? parts[i] : ".");
}

输出:

foooooo..
...
...
...
...

关于c# - 非特例,数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422751/

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