Pocok5

Untitled

Jun 4th, 2021
709
13 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class Data<T>
  4. {
  5.     public T[] Elems;
  6.  
  7.     public Data()
  8.     {
  9.         //You'd never initialize an array with 0 length but whatever floats the teacher's boat
  10.         Elems = new T[0];
  11.     }
  12.     public Data(T[] elems)
  13.     {
  14.         Elems = elems;
  15.     }
  16.  
  17.     //Make the method itself generic to get your return type.
  18.     //We'll depend on automatic type inference to fill in the generic from the return type of the provided
  19.     //lambda functions in Main() => what should be dataInt.Convert<string>(s => s + "!"); can be written as dataInt.Convert(s => s + "!");
  20.     //because the compiler can see that int s=>s+"!" returns a string so it can guess that TResult should be string
  21.     public TResult[] Convert<TResult>(Func<T, TResult> function)
  22.     {
  23.         var resultArr = new TResult[Elems.Length];
  24.         for (int i = 0; i < Elems.Length; i++)
  25.         {
  26.           //Call the lambda on each element to get the thing to put in the result array
  27.             resultArr[i] = function(Elems[i]);
  28.         }
  29.         return resultArr;
  30.     }
  31. }
  32. class Program
  33. {
  34.     public static void Main()
  35.     {
  36.         var dataString = new Data<string>();
  37.         dataString.Elems = new string[] { "Hi", "Bye" };
  38.         var convert1 = dataString.Convert(s => s.Length);
  39.         var convert2 = dataString.Convert(s => s + "!");
  40.  
  41.         var dataInt = new Data<int>(new int[] { 4, 3, 12, 5, 9 });//new Data[] {1,2,3,4};
  42.         var convert3 = dataInt.Convert(s => s + "!");
  43.         var convert4 = dataInt.Convert(s => s % 2 == 0);
  44.     }
  45. }
RAW Paste Data