如何通过反射获取和使用类/实体类型?

时间:2016-01-06 16:35:04

标签: c# .net entity-framework reflection repository

我有这些在运行时被调用的实体,我需要能够根据被字符串特定时间调用的实体类型返回IQueryable<EntityObject>。假设实体是食物类型,类名是Food,所以......

return Repository.Read<Food>();    //this is what I am trying to accomplish

但是,我不知道它是Food直到运行时,并且只是作为字符串给出,所以我使用反射:

Type t = Type.GetType(lookupEntityName);    //where lookupEntityName = "Food"

如何使用此Type t替换上面原始代码行中的“食物”:

return Repository.Read<HERE>();    // use 't' to repalce "HERE"

3 个答案:

答案 0 :(得分:0)

假设你的方法只包含一个return语句(因为你只发布了它),你可以这样做(警告:这没有经过测试):

public static IQueryable<T> Read<T>()
{
    return Repository.Read<T>();
}

你可以像这样使用它:

IQueryable<Food> food = Read<Food>();

答案 1 :(得分:0)

您必须使用MethodInfo.MakeGenericMethod Method在运行时创建通用方法。

var openMethod = typeof(Repository).GetMethod(nameof(Repository.Read), ...);
var closedMethod = openMethod.MakeGenericMethod(t);
return closedMethod.Invoke(...);

答案 2 :(得分:0)

如果需要调用泛型方法,则必须获取该函数的MethodInfo并为适当类型创建一个通用的MethodInfo。

这是执行此操作的辅助函数:

public MethodInfo GetGenericMethod(string MethodName, Type SourceType, Type TargetType)
{
    var mInfo = SourceType.GetMethod(MethodName);
    return mInfo.MakeGenericMethod(TargetType);
}

现在你可以这样做:

Type t = Type.GetType(lookupEntityName);
Type tSrc = typeof(Repository);

var result = GetGenericMethod("Read", tSrc, t).Invoke(Repository);

如果Read是静态方法,则将null传递给调用。