开发者

extension that creates StackOverflow exception

开发者 https://www.devze.com 2023-02-10 07:22 出处:网络
I wrote a function extension to a class. This extenssion function returns IList as result. Most of the times I would like to convert the IList to an array T[].

I wrote a function extension to a class. This extenssion function returns IList as result. Most of the times I would like to convert the IList to an array T[]. This is requires me to declare "using System.Linq;" in every class that converts IList to T[]. So in order to save for me the declaration of "using System.Linq;" I wrote an extension in the same class of my original extenssion (so I wouldn't have to declare "using"):

    public static T[] ToArray开发者_StackOverflow中文版<T>(this IList<T> list)
    {
        return list.ToArray();
    }

Of course that the extenssion class have "using System.Linq;", but this is the only place I need to put this declaration. The problem is that I get StackOverflow exception since the command "list.ToArray();" actually calls recoursivly to itself and not to the original ToArray. I can change the name of the function - MakeArray instead of ToArray but I would like to keep my naming conventions. Maybe do you have any solutions?


Firstly, I'd strongly advise you not to do this. You've "saved" one line (a single using directive) and added four lines which don't work. Why is a single using directive so painful to you? It's out of the way of the rest of the code, and is almost entirely innocuous... as well as providing you all the other benefits of LINQ, of course.

If you really must do this, you could just call the LINQ version explicitly:

public static T[] ToArray<T>(this IList<T> list)
{
    return System.Linq.Enumerable.ToArray(list);
}

But just don't.

0

精彩评论

暂无评论...
验证码 换一张
取 消