简体   繁体   English

通过引用传递数组扩展方法

[英]Passing array by reference to extension methods

How to pass an array to a extension method by reference. 如何通过引用将数组传递给扩展方法。

this is what i have tried but not working. 这是我尝试但不工作的。

public static void RemoveAtIndex(ref this int[] arr, int index)

You can't send extension's target object by ref. 您不能通过ref发送扩展的目标对象。 Do you relly need it? 你真的需要它吗? Is array replaced by the new one by the extension method? 是否通过扩展方法将数组替换为新数组?

Linq is used to return data, not to change data. Linq用于返回数据,而不是更改数据。 With a little different approach you replace the complete array and not changing the array. 使用稍微不同的方法,您可以替换完整的阵列而不更改阵列。

First add this little extension method: 首先添加这个小扩展方法:

public static class Extensions
{
    public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> source, int index)
    {
        return source.Where((it, i) => i != index);
    }
}

Then you could do it the "Linq way": 然后你可以做“Linq方式”:

var a = new[] {1,2,3};
a = a.SkipAt(1).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM