2011-06-21 30 views
6

我一直在努力,并试图使我的通用扩展方法的工作,但他们只是拒绝,我不知道为什么This thread didn't help me, although it should.将通用扩展方法添加到接口,如IEnumerable

当然,我抬头一看怎么样,我到处看看他们说这很简单,它应该在这个语法:
(在某些地方,我读了我需要添加“其中T:类型]”参数decleration后,但我的VS2010只是说这是一个语法错误)

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()); 
    } 
} 

但是,这是行不通的,我得到这个错误:

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

如果我再更换

public static class TExtensions 

通过

public static class TExtensions<T> 

它给出了这样的错误:

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

任何帮助将非常感激,我真的被困在这里。

回答

14

我想你错过了在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()); 
} 

注意<T>每种方法的名称后,参数列表中。这就是说这是一种通用方法,只有一个类型参数T

+0

天啊,我知道这是愚蠢的。谢谢一堆!不能相信我错过了那个> – FrieK

0

您还没有真正建立通用的方法,你都宣称非geeneric方法,返回List<T>没有定义T.您需要如下改变:

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()); 
     } 
    }