【问题标题】:Static class/method this and generics静态类/方法 this 和泛型
【发布时间】:2011-08-19 12:04:36
【问题描述】:

所以我想在 List 上调用某个方法(这是我每次在不同文件中运行的通用方法,所以我想把它放在一个静态类中)。

方法是这样的:

public static List<Item> GetRangeOrMax(this List<Item> list, int amount)
        {
            return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);
        }

问题在于,并非我需要在其上运行的每个列表都是 Item 类型。我想知道我是否能够使用泛型解决这个问题?说一下(这个List&lt;T&gt; list ...

这里的问题是该方法还必须返回该值,我想继续使用 this 关键字。如果不可能,我想我将不得不为每种类型使用不同的重载器。

【问题讨论】:

    标签: c# generics static


    【解决方案1】:

    您可以使用通用扩展方法。

    static List<T> GetRangeOrMax<T>(this List<T> list, int amount)        
    {            
          return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);        
    }
    

    【讨论】:

    • 我的静态类中出现以下错误:The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
    • @Fverswijver 您是否完全复制了我的代码?我认为您缺少方法上的类型参数。
    猜你喜欢
    • 2012-12-04
    • 2010-10-16
    • 2012-02-10
    • 2010-10-30
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多