Roy*_*ris 13 c# arrays string indexoutofrangeexception
因此??,当左手为null时,我们必须解析其右手值。什么是等价的string[]。
例如
string value = "One - Two"
string firstValue = value.Split('-')[0] ?? string.Empty;
string secondValue = value.Split('-')[1] ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)
如果我们尝试获取第三个索引或,上述示例仍然会崩溃string value = "One"。因为它不是null而是IndexOutOfRangeException被抛出。
https://docs.microsoft.com/zh-cn/dotnet/api/system.indexoutofrangeexception
那么解决上述问题的单线解决方案是什么?我想避免尝试捕获的情况,因为这会产生难看的代码。
我想string[]使用a string.Empty作为备用值来获取价值,所以我string永远不会null。
Dmi*_*nko 13
好吧,您可以尝试Linq:
using System.Linq;
...
string thirdValue = value.Split('-').ElementAtOrDefault(2) ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)
但是,您的代码有一个缺点:您始终Split使用相同的字符串。我建议提取value.Split('-'):
string value = "One - Two"
var items = value.Split('-');
string firstValue = items.ElementAtOrDefault(0) ?? string.Empty;
string secondValue = items.ElementAtOrDefault(1) ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)