Aliendreamer

methodinfo invoking method

Sep 9th, 2018
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | None | 0 0
  1. namespace OopShit
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Linq;
  6.     using System.Reflection;
  7.     using Contracts;
  8.     using Entities;
  9.     using Enums;
  10.  
  11.     public class StartUp
  12.     {
  13.         public static void Main()
  14.         {
  15.             List<Human> humans = new List<Human>();
  16.  
  17.             var human = new Farmer()
  18.             {
  19.                 Name = "gosho"
  20.             };
  21.  
  22.             string name = "Kenov";
  23.             string education = "it";
  24.             bool condemned = true;
  25.             string work = "softuni";
  26.  
  27.             Random rng = new Random();
  28.  
  29.             string habit = rng.Next(10) > 5 ? "drunk" : "literate";
  30.  
  31.             Enum.TryParse<Habits>(habit, true, out Habits result);
  32.             Human farmer = new Farmer()
  33.             {
  34.                 Name = "Nakov",
  35.                 Age = 37
  36.             };
  37.  
  38.  
  39.             var teacher = new Teacher(name, condemned, work, education, result);
  40.  
  41.             var child = new Child()
  42.             {
  43.                 Name = "Qvor",
  44.                 Age = 2
  45.             };
  46.             humans.Add(child);
  47.             humans.Add(teacher);
  48.             humans.Add(farmer);
  49.             string[] skills = new[]
  50.             {
  51.                 "Teach",
  52.                 "ApplyGrades",
  53.                 "Greet",
  54.                 "Drink",
  55.                 "Sleep",
  56.                 "Gathering",
  57.                 "KillAnimal"
  58.             };
  59.             foreach (var h in humans)
  60.             {
  61.                 Console.WriteLine(h.GetType().Name);
  62.                 var abilites = h.GetType().GetRuntimeMethods().Where(x => skills.Any((i => i == x.Name))).ToArray();
  63.                 foreach (var a in abilites)
  64.                 {
  65.                     var hhh = a.Name.Split();
  66.                     Type testType = h.GetType();
  67.                     object testInstance = Activator.CreateInstance(testType);
  68.                     MethodInfo toInvoke = testType.GetMethod(hhh[0]);
  69.                     toInvoke.Invoke(testInstance, null);
  70.                 }
  71.  
  72.             }
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment