Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过反射获取和使用类/实体类型?_C#_.net_Entity Framework_Reflection_Repository - Fatal编程技术网

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

C# 如何通过反射获取和使用类/实体类型?,c#,.net,entity-framework,reflection,repository,C#,.net,Entity Framework,Reflection,Repository,我有这些在运行时被调用的实体,我需要能够根据在特定时间被字符串调用的实体类型返回IQueryable。假设实体是食物类型,类名是food,所以 return Repository.Read<Food>(); //this is what I am trying to accomplish 如何使用此类型t替换上面原始代码行中的“食品”: return Repository.Read<HERE>(); // use 't' to repalce "HERE"

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

return Repository.Read<Food>();    //this is what I am trying to accomplish
如何使用此
类型t
替换上面原始代码行中的“食品”:

return Repository.Read<HERE>();    // use 't' to repalce "HERE"
return Repository.Read();//使用“t”重新拼贴“此处”

假设您的方法只包含一个return语句(因为您只发布了该语句),您可以执行类似的操作(警告:未测试该语句):

公共静态IQueryable Read()
{
返回Repository.Read();
}
你可以这样使用它:

IQueryable<Food> food = Read<Food>();
IQueryable food=Read();
您必须在运行时使用创建泛型方法

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

如果需要调用泛型方法,则必须获取该函数的MethodInfo,并为appropiate类型创建泛型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传递给invoke

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);