按类型调用泛型方法,其中类型是接口
Invoke generic method by type where type is interface
基本上我想做很简单的事情。我想调用通用方法,其中通用限制由接口 - ICollectionEntity 给出。
这是我的控制器的操作 - 它是用于开发目的的临时解决方案。
public class HomeController : BaseController
{
protected ICollectionsOrchestration collections;
public ActionResult Collection(string id)
{
var type = collections.GetType(id);
using (var uow = UnitOfWorkFactory.Create())
{
try
{
MethodInfo method = collections.GetType().GetMethods().FirstOrDefault(f =>
f.Name.Equals("Fetch") && f.GetParameters().Count() == 0);
MethodInfo generic = method.MakeGenericMethod(type);
var data = (IEnumerable<ICollectionEntity>) generic.Invoke(collections, null);
return View(data);
}
catch (Exception ex)
{
var msg = ex.Message;
}
}
return View();
}
}
这里是ICollectionsOrchestration接口和ICollectionEntity的具体例子。
public interface ICollectionsOrchestration
{
Type GetType(string type);
IEnumerable<T> Fetch<T>() where T : ICollectionEntity;
}
public class Collection : ICollectionEntity { }
public partial class Language : Collection { }
但是在线 MethodInfo generic = method.MakeGenericMethod(type);
我得到了异常:
GenericArguments[0], 'Idea.Data.Collections.Language', on 'System.Collections.Generic.IEnumerable`1[T] FetchT' violates the constraint of type 'T'.
但是当我将通用限制更改为 Collection
时,它就起作用了。
那么,你能告诉我为什么它适用于具体 class 但不适用于接口吗?
啊,我有 2 个接口 ICollectionEntity
,每个接口都在不同的项目内部解决方案和 HomeController 中,我都将其用于两个项目命名空间。谢谢指教。
基本上我想做很简单的事情。我想调用通用方法,其中通用限制由接口 - ICollectionEntity 给出。 这是我的控制器的操作 - 它是用于开发目的的临时解决方案。
public class HomeController : BaseController
{
protected ICollectionsOrchestration collections;
public ActionResult Collection(string id)
{
var type = collections.GetType(id);
using (var uow = UnitOfWorkFactory.Create())
{
try
{
MethodInfo method = collections.GetType().GetMethods().FirstOrDefault(f =>
f.Name.Equals("Fetch") && f.GetParameters().Count() == 0);
MethodInfo generic = method.MakeGenericMethod(type);
var data = (IEnumerable<ICollectionEntity>) generic.Invoke(collections, null);
return View(data);
}
catch (Exception ex)
{
var msg = ex.Message;
}
}
return View();
}
}
这里是ICollectionsOrchestration接口和ICollectionEntity的具体例子。
public interface ICollectionsOrchestration
{
Type GetType(string type);
IEnumerable<T> Fetch<T>() where T : ICollectionEntity;
}
public class Collection : ICollectionEntity { }
public partial class Language : Collection { }
但是在线 MethodInfo generic = method.MakeGenericMethod(type);
我得到了异常:
GenericArguments[0], 'Idea.Data.Collections.Language', on 'System.Collections.Generic.IEnumerable`1[T] FetchT' violates the constraint of type 'T'.
但是当我将通用限制更改为 Collection
时,它就起作用了。
那么,你能告诉我为什么它适用于具体 class 但不适用于接口吗?
啊,我有 2 个接口 ICollectionEntity
,每个接口都在不同的项目内部解决方案和 HomeController 中,我都将其用于两个项目命名空间。谢谢指教。