添加通用扩展方法,接口,如IEnumerable的 [英] Adding generic extension methods to interfaces like IEnumerable

查看:198
本文介绍了添加通用扩展方法,接口,如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.

当然,我抬头一看怎么样,我到处看看他们说这很简单,它应该是在此语法:

(在一些地方,我读了我需要添加其中T:[类型]。参数decleration后,但我的VS2010只是说这是一个语法错误)

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:

类型或命名空间名称'T'可以
无法找到(是否缺少使用
指令或程序集引用?)

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>



它给这个错误:

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.

推荐答案

我觉得你缺少的是制作的方法通用在 T

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

请注意在< T> 每种方法的名称后,参数列表中。那说,这是用一个类型参数, T 泛型方法。

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.

这篇关于添加通用扩展方法,接口,如IEnumerable的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆