【问题标题】:Instantiate a List<class> from textual class name从文本类名实例化 List<class>
【发布时间】:2017-10-25 02:16:03
【问题描述】:

我想知道是否有可能从文本类名实例化一个实例列表。 例如,我有以下代码:

List<Person> Persons;

我希望对某些对象的指定类名进行这种控制:

string ClassName = "Person";
List<ClassName> Persons;

如果有使用反射的可能性,请帮助我,谢谢。

【问题讨论】:

  • 听起来像是 XY 问题,你最终想做什么?

标签: c# class reflection types instance


【解决方案1】:

以下代码将按照您的要求执行 - 在 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” " 但是如何在没有硬代码的情况下投射它?再次非常感谢!
  • 除非您在编译时知道类型(显然!!),否则您不能将其转换为编译时类型。您几乎只能使用反射方法来操作列表。如果您提出实际要求,我们可以为您提供更好的帮助!
  • @RB,我添加了另一个示例,这是我需要做的,避免硬代码并控制任何对象只需指定类{entity or repository}的名称,我知道我没有'没有解释好,对不起,非常感谢你
猜你喜欢
  • 2012-04-08
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 2011-06-29
  • 1970-01-01
相关资源
最近更新 更多