Is it possible to extend arrays in C#?

前端 未结 3 886
情歌与酒
情歌与酒 2020-12-10 03:09

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

I am planning to add a method to arrays that converts it to a IEnumera

3条回答
  •  悲哀的现实
    2020-12-10 03:45

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

    public static void Extension(this string[] array)
    {
      // Do stuff
    }
    
    // or:
    
    public static void Extension(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.

提交回复
热议问题