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

时间:2012-02-11 05:37:28

标签: asp.net visual-studio-2010 linq

我已经编写了以下代码来找出丢失的序列,但我收到错误,因为我提到这是我的代码

public partial class Missing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    List<int> daysOfMonth =
       new List<int>() { 6, 2, 4, 1, 9, 7, 3, 10, 15, 19, 11, 18, 13, 22, 24, 20, 27, 31, 25, 28 };
    Response.Write("List of days:");
    foreach (var num in daysOfMonth)
    {
        Response.Write(num);
    }
    Response.Write("\n\nMissing days are: ");
    // Calling the Extension Method in the List of type int 
    foreach (var number in daysOfMonth.FindMissing()){Response.Write(number);}
}
public static IEnumerable<int> FindMissing(this List<int> list)
{
    // Sorting the list
    list.Sort();
    // First number of the list
    var firstNumber = list.First();
    // Last number of the list
    var lastNumber = list.Last();
    // Range that contains all numbers in the interval
    // [ firstNumber, lastNumber ]
    var range = Enumerable.Range(firstNumber, lastNumber - firstNumber);
    // Getting the set difference
    var missingNumbers = range.Except(list);
    return missingNumbers;
}

}

我收到如下错误Extension method must be defined in a non-generic static class任何人都可以帮助我

2 个答案:

答案 0 :(得分:19)

如错误所述,扩展方法只能在非泛型静态类上声明。您正在尝试在FindMissing类中声明Missing方法,该方法不是非泛型静态类。

您有两种选择:

  1. 使该方法成为常规方法,在这种情况下,它可以保留在Missing
  2. 声明另一个类,可能是MissingExtensions,以包含方法
  3. 这是第二个选项的样子:

    public static class MissingExtensions
    {
        public static IEnumerable<int> FindMissing(this List<int> list)
        {
            // ...
        }
    }
    

答案 1 :(得分:2)

这是你必须根据Bryan watts回答

写的内容
public partial class Missing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
     // Your code
}
}

public static class MissingExtensions
{
    public static IEnumerable<int> FindMissing(this List<int> list)
    {
        // ...
    }
}