是否可以在 C# 中扩展数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1183083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:15:20  来源:igfitidea点击:

Is it possible to extend arrays in C#?

c#.netarraysextension-methodsienumerable

提问by Jader Dias

I'm used to add methods to external classes like IEnumerable. But can we extend Arrays in C#?

我习惯于向 IEnumerable 等外部类添加方法。但是我们可以在 C# 中扩展数组吗?

I am planning to add a method to arrays that converts it to a IEnumerable even if it is multidimensional.

我计划向数组添加一个方法,即使它是多维的,也可以将其转换为 IEnumerable。

Not related to How to extend arrays in C#

如何在 C# 中扩展数组无关

采纳答案by maciejkow

static class Extension
{
    public static string Extend(this Array array)
    {
        return "Yes, you can";
    }
}

class Program
{

    static void Main(string[] args)
    {
        int[,,,] multiDimArray = new int[10,10,10,10];
        Console.WriteLine(multiDimArray.Extend());
    }
}

回答by Jader Dias

I did it!

我做到了!

public static class ArrayExtensions
{
    public static IEnumerable<T> ToEnumerable<T>(this Array target)
    {
        foreach (var item in target)
            yield return (T)item;
    }
}

回答by JulianR

Yes. Either through extending the Arrayclass as already shown, or by extending a specific kind of array or even a generic array:

是的。通过扩展Array已经显示的类,或者通过扩展特定类型的数组甚至通用数组:

public static void Extension(this string[] array)
{
  // Do stuff
}

// or:

public static void Extension<T>(this T[] array)
{
  // Do stuff
}

The last one is not exactly equivalent to extending Array, as it wouldn't work for a multi-dimensional array, so it's a little more constrained, which could be useful, I suppose.

最后一个并不完全等同于 extends Array,因为它不适用于多维数组,所以它受到了更多的限制,我想这可能很有用。