我有一个通用界面:
public interface IGeneric<T>
{
Method1(T t);
Method2(T t);
}
使用以下代码,我动态地基于实体类型创建IGeneric<T>
的实例:
var entityType = entity.GetType();
var genericType = typeof(IGeneric<>).MakeGenericType(entityType);
var result = Activator.CreateInstance(genericType);
例如,如果我的实体是Order
,则结果为IGeneric<Order>
。
现在,我如何调用结果的方法,例如我想调用Method1()
:
result.Method1();
但Method1()
无法访问。
答案 0 :(得分:1)
以下示例显示如何调用位于通用接口中的方法:
using System;
public interface IMyInterface<T>
{
T Method1(T input);
}
public class MyImpl : IMyInterface<int>
{
public int Method1(int input)
{
return input * 2;
}
}
public class Test
{
public static void Main()
{
// Concrete type that implements the interface
Type implType = typeof(MyImpl);
// Type of generic interface
Type genType = typeof(IMyInterface<>);
// Interface for int
Type concType = genType.MakeGenericType(typeof(int));
// Create instance
object inst = Activator.CreateInstance(implType);
// Retrieve member that you want to call
var member = concType.GetMethod("Method1");
// Invoke member on instance
var result = member.Invoke(inst, new object[] { 123 });
Console.WriteLine("{0} --> {1}", 123, result);
}
}
您可以运行和编辑示例here。
答案 1 :(得分:0)
我认为任何知道如何解决类型的IoC container框架都是您正在寻找的东西。首先open generic types can be registered, then their inmplementations can be resolved。
根据您的代码块,我建议您使用以下方法。它使用Activator
创建继承Repository<T>
的{{1}}实例。 IRepository<T>
接口提供了将IRepository
转换为非泛型类型和调用result
方法而无需反射的功能。:
Insert