我想调用一些方法从不同的存储库,并具有相同的类型List<>
作为结果,但我不知道如何施放没有硬编码的结果,以及如何使用foreach
对这个结果,这里的例子如下:反射:如何从使用反射调用的方法获得结果(并对其进行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");
}
}
这是不可能的,你不能让**编译器**推断你在** runtime **处提供的类型。你需要在**编译时提供泛型类型参数 - 使用强类型的时候。 – HimBromBeere
但是,您当然可以将您的结果转换为非泛型的“IEnumerable”接口并重复此操作。或者创建一个接口,让列表中所有可能的类型实现并转换为List。 –
HimBromBeere
您好@HimBromBeere,我不确定要理解好,我是C#中的新成员,请给我举一个例子来说明您提到的内容。非常感谢 –