我有两种类型 Person 和 Organization 都继承自 IContact
。
我有一个方法,可以根据某种逻辑返回这些类型之一
private Type GetPersonOrOrganisation(string some variable)
{
either returns Person or Organisation type
}
我有一个方法可以查询数据库中的人员或组织:
public static IQueryable<T> Query<T>(this IUow uow) where T : IContact
{
return uow.Query<T>();
}
我的问题是如何使用从 GetPersonOrOrganization
返回的类型来调用查询。
所以说:
var contactType = GetPersonOrOrganisation(string some variable);
var contact = Query<contactType>();
其中 contactType 为“个人”或“组织”。
显然这不会编译,这是我的问题。如何根据 GetPersonOrOrganization
返回的内容从数据库中查询正确的类型。
最佳答案
在Type
之间移动泛型是一个主要的痛苦;不重构的唯一答案是:反射;像这样:
var method = typeof(SomeType).GetMethod("Query").MakeGenericMethod(contactType);
// this is to getch your Query<T>(this IUow) method
var contact = (IContact)method.Invoke(null, new object[] { uow });
这太可怕了。如果可能的话,我建议重写你的 Query<T>
方法为Query(Type type)
方法(返回 IContact
),它仍然简单地允许通用 Query<T>
现有代码的辅助方法,通过 return (T) Query(typeof(T));
。然而,反之则不然。
如果您传递 T
类型的实例该方法中,您可以使用 dynamic
来简化此过程。为您执行类型/泛型/方法解析。
关于c# - 如何使用从不同方法返回的类型来调用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15379523/