Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果数组元素不存在,则返回null_C#_Arrays_.net Core_Nullable - Fatal编程技术网

C# 如果数组元素不存在,则返回null

C# 如果数组元素不存在,则返回null,c#,arrays,.net-core,nullable,C#,Arrays,.net Core,Nullable,如果数组元素不存在,是否有简单的方法获取值“null” 例如,在下面的代码中,sArray有3个元素,前3个对SomeMethod work的调用打印为true,而第4个调用SomeMethodsArray[3];给了我一个索引的例外。有没有办法使第四次调用SomeMethod print false static void Main(string[] args) { int[] sArray = new int[]{1,2,3}; SomeMet

如果数组元素不存在,是否有简单的方法获取值“null”

例如,在下面的代码中,sArray有3个元素,前3个对SomeMethod work的调用打印为true,而第4个调用SomeMethodsArray[3];给了我一个索引的例外。有没有办法使第四次调用SomeMethod print false

    static void Main(string[] args)
    {
        int[] sArray = new int[]{1,2,3};
        SomeMethod(sArray[0]);
        SomeMethod(sArray[1]);
        SomeMethod(sArray[2]);
        SomeMethod(sArray[3]);
    }
    static void SomeMethod(int? s) => Console.WriteLine(s.HasValue);
^我更喜欢单线表达

SomeMethod(sArray.Skip(3).Select(z => (int?)z).FirstOrDefault());
是以下各项的有效替代品:

SomeMethod(sArray[3]);
前者将调用带有null的SomeMethod,而后者将在数组没有至少4个条目时抛出异常

在Skip3中,可以将3更改为要从数组中检索的任何索引。需要选择将int投影为int?因此FirstOrDefault返回第四个元素或null

如果您不想使用LINQ,则可以使用:

SomeMethod(sArray.Length > 3 ? sArray[3] : (int?)null);
相反

或考虑使用:

foreach (var entry in sArray.Take(4))
{
    SomeMethod(entry);
}

要循环最多4个数组元素,如果少于4个,则可以正常工作-只需对SomeMethod进行较少的调用。

扩展方法如何

public static T? TryGet<T>(this T[] source, int index) where T: struct
{
    if (0 <= index && index < source.Length)
    {
        return source[index];
    }
    else
    {
        return null;
    }
}
有一种Linq方法

要以返回null的方式使用它,需要将数组的基础类型更改为可为null的int:

    int?[] sArray = new int?[]{1,2,3};
    SomeMethod(sArray.ElementAtOrDefault(1000));

在这种情况下,我建议您在代码中的某个地方创建一个扩展,如下所示

static class ArrExt
{
    public static int? Get(this int[] arr, int i)
    {
        return (i >= 0 && i < arr.Length) ? arr[i] : default(int?);
    }
}
好的,我知道这不是一个单行解决方案,但对程序员和计算机来说都比较容易。

C中的数组有一个.Length属性,在尝试将项从一个方法传递到某个方法之前可以检查该属性,典型的方法是循环数组的每个元素,而不是猜测索引是否有效:

for (int i = 0; i < sArray.Length; i++) 
{
    SomeMethod(sArray[i]); 
}
然后在使用中,您将分别传递数组本身和索引,而不是传递带有无效索引的数组项,该索引将始终引发IndexOutOfRangeException:

static void Main()
{
    int[] sArray = new int[] { 1, 2, 3 };

    SomeMethod(sArray, 0);
    SomeMethod(sArray, 1);
    SomeMethod(sArray, 2);
    SomeMethod(sArray, 3);
    SomeMethod(null, 0);

    GetKeyFromUser("\nPress any key to exit...");
}
输出


您可以防止异常,然后为什么需要这种类型的解决方案您可以通过sArray在循环上调用somemethod它不会抛出exceptionDownvoted:这似乎是一个。C中的数组有一个.Length属性,您可以在调用somemethod之前检查该属性。典型的方法是循环遍历数组的每个元素,而不是猜测索引是否有效:对于int i=0;ifor (int i = 0; i < sArray.Length; i++) { SomeMethod(sArray[i]); }
private static void SomeMethod(int[] array, int index) => 
    Console.WriteLine(index >= 0 && index < array?.Length);
static void Main()
{
    int[] sArray = new int[] { 1, 2, 3 };

    SomeMethod(sArray, 0);
    SomeMethod(sArray, 1);
    SomeMethod(sArray, 2);
    SomeMethod(sArray, 3);
    SomeMethod(null, 0);

    GetKeyFromUser("\nPress any key to exit...");
}