[英]How to get and use class/entity type by reflection?
I have these entities that are being called at runtime and I need to be able to return an IQueryable<EntityObject>
based on the entity type being called that particular time by string. 我有在运行时被调用的这些实体,并且我需要能够基于通过字符串在特定时间调用的实体类型来返回IQueryable<EntityObject>
。 Let's say the entity is types of food and the class name is Food
, so... 假设实体是食物类型,而类名是Food
,所以...
return Repository.Read<Food>(); //this is what I am trying to accomplish
However, I don't know that it is Food
until runtime and is such only given as a string, so I use reflection: 但是,直到运行时,我才知道它是Food
,而且仅以字符串形式给出,因此我使用了反射:
Type t = Type.GetType(lookupEntityName); //where lookupEntityName = "Food"
How can I use this Type t
to replace 'Food' in the original line of code from above: 我该如何使用Type t
替换上面代码中的原始代码中的“食物”:
return Repository.Read<HERE>(); // use 't' to repalce "HERE"
Supposing that your method only contains a return statement (because you have only posted that), you could do something like this (warning: this wasn't tested): 假设您的方法仅包含一个return语句(因为您只发布了该语句),则可以执行以下操作(警告:未经测试):
public static IQueryable<T> Read<T>()
{
return Repository.Read<T>();
}
And you could use it like this: 您可以这样使用它:
IQueryable<Food> food = Read<Food>();
You have to use the MethodInfo.MakeGenericMethod Method to create your generic method at runtime. 您必须使用MethodInfo.MakeGenericMethod方法在运行时创建通用方法。
var openMethod = typeof(Repository).GetMethod(nameof(Repository.Read), ...);
var closedMethod = openMethod.MakeGenericMethod(t);
return closedMethod.Invoke(...);
If you need to call a generic method, you must get the MethodInfo of that function and create a generic MethodInfo for the appropiate type. 如果需要调用泛型方法,则必须获取该函数的MethodInfo并为适当的类型创建泛型MethodInfo。
This is a helper function to do this: 这是一个帮助函数,可以执行以下操作:
public MethodInfo GetGenericMethod(string MethodName, Type SourceType, Type TargetType)
{
var mInfo = SourceType.GetMethod(MethodName);
return mInfo.MakeGenericMethod(TargetType);
}
And now you can do this: 现在您可以执行以下操作:
Type t = Type.GetType(lookupEntityName);
Type tSrc = typeof(Repository);
var result = GetGenericMethod("Read", tSrc, t).Invoke(Repository);
If Read is an static method then pass null to the invoke. 如果Read是静态方法,则将null传递给调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.