从通用方法调用中转换结果?

Son*_*Boy 5 .net c# generics

我正在搞乱泛型,我正在尝试编写一个函数,我可以通过指定表名来调用从数据库表中加载所有内容.

我大部分都在那里; 我的通用方法似乎都可行,但我不太确定如何将结果转换为可用的结果.

到目前为止,这是该方法的核心:

private static List<EntityCodeBase> GetCodeLoadResults(CodeTables table)
{
    List<EntityCodeBase> results = new List<EntityCodeBase>();
    Assembly assm = Assembly.Load(new System.Reflection.AssemblyName("RR"));
    Type tableType = assm.GetTypes().Where(u => u.Name.ToLower() == table.ToString().ToLower()).FirstOrDefault();
    MethodInfo mi = typeof(SpecificEntity).GetMethod("LoadAll");

    mi = mi.MakeGenericMethod(tableType);
    mi.Invoke(null, null); //how can I cast the resulting object into a List<EntityCodeBase> ?

    return results;
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 5

假设SpecificEntity.LoadAll返回一个派生自某种类型的列表EntityCodeBase,则无法直接转换为a List<EntityCodeBase>但可以转换为IEnumerable<EntityCodeBase>.然后,您可以创建一个新列表:

var ecbList = (IEnumerable<EntityCodeBase>)mi.Invoke(null, null);
return list.ToList();
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以直接按名称,使用属性或使用地图从实体类型获取表名,则可能更清晰.然后你可以GetCodeLoadResults在结果类型中制作泛型,例如

private static List<T> GetCodeLoadResults() where T : EntityCodeBase
{
    Assembly assm = Assembly.Load(new System.Reflection.AssemblyName("RR"));
    Type tableType = //get table type from T
    MethodInfo mi = typeof(SpecificEntity).GetMethod("LoadAll");

    mi = mi.MakeGenericMethod(tableType);
    return (List<T>)mi.Invoke(null, null);
}
Run Code Online (Sandbox Code Playgroud)

如果您不使用.Net 4,则无法将其转换List<TDerived>为a IEnumerable<TBase>,因此您必须先强制​​转换为IEnumerable:

return ((System.Collections.IEnumerable)mi.Invoke(null, null))
    .Cast<EntityCodeBase>()
    .ToList();
Run Code Online (Sandbox Code Playgroud)