简体   繁体   中英

static/generic/non-generic definitions error

Techies-- I think I'm defining this static extension correctly for Split, I obviously am not because the message: Extension method must be defined in a non-generic static class.

This is a simple c# console program to test something. Here's what I have:

class Program
{ 
  static int Main(string[] args)
  {
    int[] numbers = new int[10000]; 
           for (int i = 0; i < numbers.Length; ++i) 
               numbers[i] = i; 

  int[][] sectionedNumbers = numbers.Split(1000); 
   .
   . //blah blah blah .. rest of code

 return 0;
 }

 public static T[][] Split<T>(this T[] arrayIn, int length)
 {
  bool even = arrayIn.Length % length == 0;
    .
    .
    . // blah blah .. more code

   return newArray;
   }

What is it that I'm doing incorrectly?

Your class Program is not static as requested by the error message.

  • Add the static directive to the class declaration:

      static class Program { // ... 
  • or move Split into another static class altogether.

Then your code should compile again.

Hello your container class must be static

Set you method in static class

public static class Extension
{
 public static T[][] Split<T>(this T[] arrayIn, int length)
 {
  bool even = arrayIn.Length % length == 0;
    .
    .
    . // blah blah .. more code

   return newArray;
   }

}

You need to define your extension method in a class, like this:

public static class ArrayExtensions
{
 public static T[][] Split<T>(this T[] arrayIn, int length) 
 { 
  bool even = arrayIn.Length % length == 0; 
    . 
    . 
    . // blah blah .. more code 

   return newArray; 
   } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM