Adding generic extension methods to interfaces like IEnumerable

走远了吗. 提交于 2020-01-14 08:45:47

问题


I've been trying and trying to make my generic extension methods work, but they just refuse to and I can't figure out why. This thread didn't help me, although it should.

Of course I've looked up how to, everywhere I see they say it's simple and it should be in this syntax:
(On some places I read that I need to add "where T: [type]" after the parameter decleration, but my VS2010 just says that's a syntax error.)

using System.Collections.Generic;
using System.ComponentModel;

public static class TExtensions
{
    public static List<T> ToList(this IEnumerable<T> collection)
    {
        return new List<T>(collection);
    }

    public static BindingList<T> ToBindingList(this IEnumerable<T> collection)
    {
        return new BindingList<T>(collection.ToList());
    }
}

But that just doesn't work, I get this error:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

If I then replace

public static class TExtensions

by

public static class TExtensions<T>

it gives this error:

Extension method must be defined in a non-generic static class

Any help will be much appreciated, I'm really stuck here.


回答1:


I think what you're missing is making the methods generic in T:

public static List<T> ToList<T>(this IEnumerable<T> collection)
{
    return new List<T>(collection);
}

public static BindingList<T> ToBindingList<T>(this IEnumerable<T> collection)
{
    return new BindingList<T>(collection.ToList());
}

Note the <T> after the name of each method, before the parameter list. That says it's a generic method with a single type parameter, T.




回答2:


Try:

public static class TExtensions
{
  public static List<T> ToList<T>(this IEnumerable<T> collection)
  {
      return new List<T>(collection);
  }

  public static BindingList<T> ToBindingList<T>(this IEnumerable<T> collection)
  {
      return new BindingList<T>(collection.ToList());
  }
}



回答3:


You have not actually created generic methods you have declared non geeneric methods that return List<T> without defining T. You need to change as below:

public static class TExtensions
    {
        public static List<T> ToList<T>(this IEnumerable<T> collection)
        {
            return new List<T>(collection);
        }

        public static BindingList<T> ToBindingList<T>(this IEnumerable<T> collection)
        {
            return new BindingList<T>(collection.ToList());
        }
    }


来源:https://stackoverflow.com/questions/6423152/adding-generic-extension-methods-to-interfaces-like-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!