2012-02-11 102 views
3

我寫了下面的代碼,找出失蹤的序列中定義,但正如我所說,這個我得到的錯誤是我的代碼擴展方法必須在非泛型靜態類

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任何一個可以幫助我

+0

的可能的複製[擴展方法必須在非泛型靜態類中定義(https://stackoverflow.com/questions/6096299/extension -methods-must-defined-in-a-non-generic-static-class) – amin 2017-08-21 05:35:20

回答

18

由於錯誤狀態,擴展方法只能在非泛型靜態類聲明。您正試圖在Missing類中聲明FindMissing方法,該類不是非泛型靜態類。

你有兩個選擇:

  1. 製作方法的常規方法,在這種情況下,它可以留在Missing
  2. 聲明另一個類,也許MissingExtensions,遏制方法

這是第二個選項的樣子:

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

我收到這個錯誤,如果我按照你的說法寫道:「擴展方法必須在頂級靜態類中定義; MissingExtensions是一個嵌套類' – Chaitanya 2012-02-11 06:12:04

+0

@Chaitanya你沒有寫,因爲他說,他沒有提到將它嵌入外部階層的事情。 – 2012-02-11 06:48:40

3

這是你必須寫爲每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) 
    { 
     // ... 
    } 
} 
相關問題