2011-06-21 17 views
6

He estado intentando y tratando de hacer que mis métodos de extensión genéricos funcionen, pero simplemente se niegan y no puedo entender por qué. This thread didn't help me, although it should.Agregando métodos de extensión genéricos a interfaces como IEnumerable

Por supuesto he admirado cómo, en todas partes veo que dicen que es simple y que debería estar en esta sintaxis:
(En algunos lugares he leído que tengo que añadir "donde T: [Tipo .]" después de la decleration parámetro, pero mi VS2010 sólo dice que es un error de sintaxis)

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

pero eso simplemente no funciona, me sale este error:

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

si yo sustituyo

public static class TExtensions 

por

public static class TExtensions<T> 

se da este error:

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

será muy apreciada Cualquier ayuda, realmente estoy atascado aquí.

Respuesta

14

Creo que lo que se está perdiendo es hacer los métodos genérica en 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()); 
} 

Nota del <T> después del nombre de cada método, antes de que la lista de parámetros. Eso dice que es un método genérico con un parámetro de tipo único, T.

+0

Oh, Dios sabía era algo estúpido como eso. ¡Gracias un montón! No puedo creer que me perdí eso>< – FrieK

1

Proveedores:

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

No ha creado realmente métodos genéricos que han declarado métodos no geeneric que devuelven List<T> sin definir T. Es necesario cambiar de la siguiente manera:

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