c# - 数组访问的安全元素

标签 c# .net arrays tryparse

访问数组元素的安全方法是什么,而不会抛出 IndexOutOfRangeException,例如 TryParseTryRead,使用扩展方法或 LINQ ?

最佳答案

使用System.Linq ElementAtOrDefault方法。它在不抛出异常的情况下处理超出范围的访问。 如果索引无效,它会返回一个默认值。

int[] array = { 4, 5, 6 };
int a = array.ElementAtOrDefault(0);    // output: 4
int b = array.ElementAtOrDefault(1);    // output: 5
int c = array.ElementAtOrDefault(-1);   // output: 0
int d = array.ElementAtOrDefault(1000); // output: 0

另请参阅:DotNetPearls - ElementAt

关于c# - 数组访问的安全元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/693353/

相关文章:

c - 在 C 中将方阵提高到 N 次方

javascript - 使用 Javascript 搜索数组中的项目

Python 嵌套循环仅适用于第一遍

c# - 连接到安全 WebService

c# - DependencyProperty 绑定(bind)问题

c# - 为什么类 Program 的默认构造函数 Never executed?

c# - 接口(interface)的通用类型约束?

c# - MVC 6 没有为未定义的路由抛出异常

c# - 关系 - EF Core

c# - 使用linq连接2个具有不同结构的表