Csharp/C Sharp/Generics/Generic Method

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

A prototypical generic method

<source lang="csharp">

using System; public class Starter{

   public static void Main(){
      MethodA<int>(20);
   }
   public static void MethodA<T>(T param) {
      Console.WriteLine(param.GetType().ToString());
   }

}


      </source>


Demonstrate a generic method

<source lang="csharp"> using System; class ArrayUtils {

 public static bool copyInsert<T>(T e, int idx, T[] src, T[] target) {
   if(target.Length < src.Length+1)
     return false;
   for(int i=0, j=0; i < src.Length; i++, j++) {
     if(i == idx) {
       target[j] = e;
       j++;
     }
     target[j] = src[i];
   }
   return true;
 }

} class Test {

 public static void Main() {
   int[] nums = { 1, 2, 3 };
   int[] nums2 = new int[4];
   Console.Write("Contents of nums: ");
   foreach(int x in nums)
     Console.Write(x + " ");
   Console.WriteLine();
   ArrayUtils.copyInsert(99, 2, nums, nums2);
   Console.Write("Contents of nums2: ");
   foreach(int x in nums2)
     Console.Write(x + " ");
   Console.WriteLine();
   string[] strs = { "Generics", "are", "powerful."};
   string[] strs2 = new string[4];
   Console.Write("Contents of strs: ");
   foreach(string s in strs)
     Console.Write(s + " ");
   Console.WriteLine();
   ArrayUtils.copyInsert("in C#", 1, strs, strs2);
   Console.Write("Contents of strs2: ");
   foreach(string s in strs2)
     Console.Write(s + " ");
 }

}

      </source>


Generic methods can overload nongeneric methods

<source lang="csharp"> using System; public class Starter{

       public static void Main(){
           MethodA(5);
           MethodA(5.0);
       }
       public static void MethodA<T>(T arg) {
           Console.WriteLine("ZClass.MethodA(T arg)");
       }
       public static void MethodA(int arg) {
           Console.WriteLine("ZClass.MethodA(int arg)");
       }
       public static void MethodA() {
           Console.WriteLine("ZClass.MethodA()");
       }

}

      </source>


This is a prototypical generic method:

<source lang="csharp"> using System;

public class Starter {

   public static void Main() {
       MyClass.MethodA<int>(20);
   }

} public class MyClass {

   public static void MethodA<T>(T param) {
       Console.WriteLine(param.GetType().ToString());
   }

}

</source>