Extension method must be defined in a non-generic static class

一世执手 提交于 2020-01-03 16:15:08

问题


I have written the following code to find out the missing sequence but i am getting the error as i mentioned this is my code

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

}

I am getting the error as follows Extension method must be defined in a non-generic static class can any one help me


回答1:


As the error states, extension methods can only be declared on a non-generic static class. You are attempting to declare the FindMissing method in the Missing class, which is not a non-generic static class.

You have two options:

  1. Make the method a normal method, in which case it can stay in the Missing class
  2. Declare another class, perhaps MissingExtensions, to contain the method

This is what the second option would look like:

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



回答2:


This is what you have to write as per Bryan watts answer

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)
    {
        // ...
    }
}


来源:https://stackoverflow.com/questions/9238114/extension-method-must-be-defined-in-a-non-generic-static-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!