【发布时间】:2017-05-25 08:10:24
【问题描述】:
我想从不同的存储库中调用一些方法并具有相同类型的 List<> 作为结果,但我不知道如何在没有硬代码的情况下转换结果以及如何在此结果上使用 foreach,这里下面的例子:
class Person
{
public string Name { get; set; }
}
class Animal
{
public string Name { get; set; }
}
class PersonRepository
{
public List<Person> GetPersons()
{
List<Person> list = new List<Person>();
//Some processing...
return list;
}
}
class AnimalRepository
{
public List<Animal> GetAnimals()
{
List<Animal> list = new List<Animal>();
//Some processing...
return list;
}
}
public class ReflectionClass
{
public List<T> GetResultFromMethodInvoked<T>(string entityName, string repositoryName, string methodName)
{
List<T> lists = new List<T>();
Type entity_type = Type.GetType("Entities." + entityName + " ,Entities");
Type repository = Type.GetType("Crud." + repositoryName + ", Crud");
MethodInfo method = repository.GetType().GetMethod(methodName);
var r= method.Invoke(repository, parameters);
Convert.ChangeType(r, typeof(List<>).MakeGenericType(new Type[] { entity_type }));
lists = (List<T>)r;
return lists;
}
}
class Program
{
static void Main(string[] args)
{
ReflectionClass reflection = new ReflectionClass();
/* Should have List<Person> as RESULT */
reflection.GetResultFromMethodInvoked("Person", "PersonRepository", "GetPersons");
/* Should have List<Animal> as RESULT */
reflection.GetResultFromMethodInvoked("Animal", "AnimalRepository", "GetAnimals");
}
}
【问题讨论】:
-
这是不可能的,你不能让编译器推断你在运行时提供的类型。您必须在编译时提供通用类型参数以使用强类型。
-
但是,您当然可以将结果转换为非通用
IEnumerable-interface 并对其进行迭代。或者创建一个接口,列表中所有可能的类型都实现并转换为List<TheInterface>。 -
嗨@HimBromBeere,我不太清楚,我是C#的新手,你能举个例子吗?非常感谢
标签: c# reflection casting generic-list