数组访问的安全元素

aba*_*hev 3 .net c# arrays tryparse

什么是访问数组元素,没有抛出安全的方法IndexOutOfRangeException,有点像TryParse,TryRead使用扩展方法或LINQ?

sto*_*omy 14

使用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
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 8

您可以使用以下扩展方法.

public static bool TryGetElement<T>(this T[] array, int index, out T element) {
  if ( index < array.Length ) {
    element = array[index];
    return true;
  }
  element = default(T);
  return false;
}
Run Code Online (Sandbox Code Playgroud)

例:

int[] array = GetSomeArray();
int value;
if ( array.TryGetElement(5, out value) ) { 
  ...
}
Run Code Online (Sandbox Code Playgroud)