Generic method in a non-generic class?

2020-08-09 05:52发布

I'm sure I've done this before, but can't find any example of it! Grrr...

For example, I want to convert an IList<T> into a BindingList<T>:

public class ListHelper
{
    public static BindingList<T> ToBindingList(IList<T> data)
    {
        BindingList<T> output = new BindingList<T>();

        foreach (T item in data)
            output.Add(item);

        return output;
    }
}

标签: c# generics
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-08-09 06:40
ToBindingList <T> (...)

public class ListHelper
{
    public static BindingList<T> ToBindingList<T>(IList<T> data)
    {
        BindingList<T> output = new BindingList<T>();

        foreach (T item in data)
        {
            output.Add(item);
        }

        return output;
    }
}
查看更多
成全新的幸福
3楼-- · 2020-08-09 06:50

You can do this by extension method and it would be better.

public static class Extensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> list) 
    {
        BindingList<T> bindingList = new BindingList<T>();

        foreach (var item in list)
        {
            bindingList.Add(item);
        }

        return bindingList;
    }
}
查看更多
ら.Afraid
4楼-- · 2020-08-09 06:51

Wouldn't this be simpler?

public static class Extensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> list)
    {
        return new BindingList<T>(list);
    }
}

It's so simple that we don't need an extension method ...

Am I missing something?

查看更多
登录 后发表回答