我想知道是否有可能從文本類名稱實例化實例列表。 例如,我有下面這段代碼:從文本類名稱實例化列表<class>
List<Person> Persons;
我想有一些對象這種對specifiying類名控制:
string ClassName = "Person";
List<ClassName> Persons;
如果有一些可能使用反射,請幫助我,謝謝。
我想知道是否有可能從文本類名稱實例化實例列表。 例如,我有下面這段代碼:從文本類名稱實例化列表<class>
List<Person> Persons;
我想有一些對象這種對specifiying類名控制:
string ClassName = "Person";
List<ClassName> Persons;
如果有一些可能使用反射,請幫助我,謝謝。
以下代碼將按照您的要求進行操作 - 在Linqpad中運行以查看輸出。關鍵的方法是Type.MakeGenericType。
如果您給出您的實際用例或要求,我可以調整代碼以使其對您更有用。
void Main()
{
string className = "UserQuery+Person";
Type personType = Type.GetType(className);
Type genericListType = typeof(List<>);
Type personListType = genericListType.MakeGenericType(personType);
IList personList = Activator.CreateInstance(personListType) as IList;
// The following code is intended to demonstrate that this is a real
// list you can add items to.
// In practice you will typically be using reflection from this point
// forwards, as you won't know at compile time what the types in
// the list actually are...
personList.Add(new Person { Name = "Alice" });
personList.Add(new Person { Name = "Bob" });
foreach (var person in personList.Cast<Person>())
{
Console.WriteLine(person.Name);
}
}
class Person
{
public string Name { get; set;}
}
如果'className ==「SomeClassNameOtherThanPerson」'?你的代碼只適用於Person類而不適用於任何其他類。 –
Activator.CreateInstance之後的所有內容都旨在證明這是一個真正的列表,您可以添加到這個列表中 - 因爲他沒有解釋他打算如何使用此列表,所以純粹只是爲了演示如何使用它。我編輯了我的代碼以清楚地說明。 –
非常感謝@ChrisDunaway,它可以幫助我,但是是的,它只會與「Person Class」一起工作,這裏的問題是您在personList上使用「cast」作爲書寫的「personList.Cast
聽起來像一個XY問題,你最終想做什麼? – Sweeper