我在School
中試圖創建一個對象列表Student
。 Student
而不是School
也可以有Teacher
作爲列表。我想在啓動類時使用類名作爲參數,而不是實際的類類型作爲參數。如何使用字符串值傳遞類型爲<T>參數的類型?
public class Program
{
static void Main(string[] args)
{
//School object with list of student
var schoolWithStudent = SchoolWithOject("Student");
//School object with list of teacher
var schoolWithTeacher = SchoolWithOject("Teacher");
}
public static object SchoolWithOject(string objType)
{
var objType = Type.GetType("objType");
var school = new School<objType>();
return school;
}
}
public class School<T>
{
public int Id;
public string Name;
private List<T> _components;
public School()
{
_components = new List<T>();
}
}
public class Student
{
public int Id;
public string Name;
}
public class Teacher
{
int Id;
string Name;
}
你有沒有問過自己,爲什麼你想呢?你的代碼看起來並不動態,「新學校();有什麼問題? –
maccettura
另外,如果教師和學生具有相同的屬性(或共享一些屬性),它應該被抽象爲一個基類或一個接口(如'Person'或其他)。這樣,你可以限制你的'學校'只允許通用抽象 –
maccettura
檢查此https://stackoverflow.com/questions/2194949/how-to-use-class-name-as-parameter-in-c-sharp – Dahico