Оставляю кусочек кода себе на память. Универсальный, но в моем случае требует костылей.
#region Generic public void CreateLang(TModel langModel, out IEnumerable diff) { Type entityType = this.TypesModelEntity[typeof(TModel)]; //вот костыль var langType = this.TypesEntityLang[entityType]; //и еще один Type genericClass = typeof(EFLangRepository); Type constructedClass = genericClass.MakeGenericType(typeof(TModel), entityType, langType); object repo = Activator.CreateInstance(constructedClass); diff = new List(); object[] args = new object[] { langModel, diff }; MethodInfo magicMethod = constructedClass.GetMethod("CreateLang"); object magicValue = magicMethod.Invoke(repo, args); diff = args[1] as List; } #endregion
Про создание экземпляра объекта
using System; using System.Reflection; public class Generic { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Type genericClass = typeof(IReadOnlyDictionary); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
И MSDN
https://msdn.microsoft.com/ru-ru/library/a89hcwhh(v=vs.110).aspx
public class MagicClass { private int magicBaseValue; public MagicClass() { magicBaseValue = 9; } public int ItsMagic(int preMagic) { return preMagic * magicBaseValue; } } public class TestMethodInfo { public static void Main() { // Get the constructor and create an instance of MagicClass Type magicType = Type.GetType("MagicClass"); ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes); object magicClassObject = magicConstructor.Invoke(new object[]{}); // Get the ItsMagic method and invoke with a parameter value of 100 MethodInfo magicMethod = magicType.GetMethod("ItsMagic"); object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100}); Console.WriteLine("MethodInfo.Invoke() Example\n"); Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue); } }
Вызов метода
http://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method
MethodInfo method = typeof(Sample).GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null);
Про generic-метод
http://stackoverflow.com/questions/2247553/how-to-pass-variable-of-type-type-to-generic-parameter
var method = typeof(MetaDataUtil) .GetMethod("GetColumnasGrid") .MakeGenericMethod(new [] { type }) .Invoke(null, null);