【问题标题】:Adding generic extension methods to interfaces like IEnumerable向 IEnumerable 等接口添加通用扩展方法
【发布时间】:2011-06-21 09:32:05
【问题描述】:

我一直在尝试让我的通用扩展方法工作,但他们只是拒绝,我无法弄清楚为什么This thread didn't help me, although it should.

当然,我已经查找了如何操作,无论我在哪里看到他们都说这很简单,并且应该采用以下语法:
(在某些地方我读到我需要在参数声明后添加“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());
    }
}

但这不起作用,我收到此错误:

类型或命名空间名称“T”可以 找不到(您是否缺少使用 指令还是程序集引用?)

如果我再替换

public static class TExtensions

通过

public static class TExtensions<T>

它给出了这个错误:

扩展方法必须定义在一个 非泛型静态类

任何帮助将不胜感激,我真的被困在这里了。

【问题讨论】:

    标签: c# generics extension-methods


    【解决方案1】:

    我认为您缺少的是使 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());
    }
    

    注意每个方法名称之后,参数列表之前的&lt;T&gt;。也就是说,它是一个具有单个类型参数 T 的泛型方法。

    【讨论】:

    • 天哪,我就知道这是愚蠢的事情。非常感谢!不敢相信我错过了>
    【解决方案2】:

    试试:

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

    【讨论】:

      【解决方案3】:

      您实际上还没有创建泛型方法,您声明了返回List&lt;T&gt;而不定义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());
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-17
        • 2012-03-05
        • 1970-01-01
        • 2011-06-02
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多