[英]Adding generic extension methods to interfaces like IEnumerable
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.) (在某些地方,我读到我需要在参数清除之后添加“ where T:[type]”,但是我的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());
}
}
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?) 找不到类型或名称空间名称“ T”(是否缺少using指令或程序集引用?)
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. 任何帮助将不胜感激,我真的被困在这里。
I think what you're missing is making the methods generic in T
: 我认为您所缺少的是使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. 注意每个方法的名称后,参数列表前的<T>
。 That says it's a generic method with a single type parameter, T
. 也就是说,这是带有单个类型参数T
的通用方法。
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());
}
}
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: 您实际上尚未创建泛型方法,而已声明返回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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.