Aliendreamer

reflection with params

Oct 29th, 2018
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1.  public IExecutable InterpretCommand(string[] data, string commandName)
  2.         {
  3.             // взимаме всички типове в програмата това е пример за command pattern
  4.             Assembly assembly = Assembly.GetCallingAssembly();
  5.             Type commandType = assembly.GetTypes()
  6.                 .FirstOrDefault(t => t.Name.ToLower() == commandName + "command");
  7.             //2 проверки дали съществува и дали абстракния интерфейс е наследствен в командата
  8.             if (commandType == null)
  9.             {
  10.                 throw new ArgumentException("Invalid command!");
  11.             }
  12.  
  13.             if (!typeof(IExecutable).IsAssignableFrom(commandType))
  14.             {
  15.                 throw new ArgumentException("invalid command!");
  16.             }
  17.             //обхождаме полетата на класа които се подават през конструктора,тук ползваме dependency injection
  18.             FieldInfo[] fieldsToInject = commandType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
  19.                 .Where(f => f.CustomAttributes.Any(ca => ca.AttributeType == typeof(InjectAttribute))).ToArray();
  20.             //activatora ползва оbject array затова създаваме array oт нужните ни обекти
  21.             object[] injectArgs = fieldsToInject.Select(f => this.serviceProvider.GetService(f.FieldType)).ToArray();
  22.             object [] constArgs=new object[]{data}.Concat(injectArgs).ToArray();
  23.             // създавме командата като пак я кастваме към интерфейса
  24.             IExecutable command = (IExecutable)Activator.CreateInstance(commandType, constArgs);
  25.             // връщаме командата.
  26.             return command;
  27.         }
Advertisement
Add Comment
Please, Sign In to add comment