我想調用一些方法從不同的存儲庫,並具有相同的類型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#中的新成員,請給我舉一個例子來說明您提到的內容。非常感謝 –