gpt4 book ai didi

c# - 创建 Array.ReturnLength() 扩展方法?

转载 作者:太空宇宙 更新时间:2023-11-03 21:34:32 24 4
gpt4 key购买 nike

我想为 System.Array 类创建一个扩展方法,它将接收一个 char[]byte[] 数组并返回它的长度。我需要这种方法以防数组为 null,并且我不想用一大堆 (arr == null) 乱扔代码? 0 : arr.Length 调用。

我想这样调用它:Array.ReturnLength(arr)

我尝试实现它,但我只在执行 arr.ReturnLength() 时看到它,而不是作为数组方法。

public static int ReturnLength(this Array arr)
{
if (arr == null)
return 0;
return arr.Length;
}

有什么想法吗?谢谢。

最佳答案

您可以使用通用扩展方法:

public static int ReturnLength<T>(this T[] arr)
{
if (arr == null)
return 0;
return arr.Length;
}

您可以将它与空引用一起使用:

string[] arr = null;
int length = arr.ReturnLength(); // 0

更新:但您的非通用扩展方法应该以相同的方式工作:

public static int ReturnLength(this Array arr)
{
if (arr == null)
return 0;
return arr.Length;
}

之所以可行,是因为扩展方法只是语法糖。实际上它们是静态方法,您也可以通过类名使用它们:

int length = MyExtensions.ReturnLength(arr);

In C#, what happens when you call an extension method on a null object?

关于c# - 创建 Array.ReturnLength() 扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409872/

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