【问题标题】:How to use Activator.CreateInstance to create instance of class when user presses button用户按下按钮时如何使用 Activator.CreateInstance 创建类的实例
【发布时间】:2014-01-25 05:09:21
【问题描述】:

class Person
{


    //Default Constructor
    public Person()
    {
        name_private = "";
        attr_private = 0.0;
    }

    //Overloaded Constructor
    public Person(string name, double attr)
    {
        name_private = name;
        attr_private = attr;
    }

    //Member Variables
    private string name_private;
    private double attr_private;


}

/////////////////////////////////////// //////////////////////////////////p>

private void createPersonBox_Click(object sender, EventArgs e)
    {

        Object obj =   Activator.CreateInstance<Person>();

        //Person person_1 = new Person();
    }

/////////////////////////////////////// ///////////////////////////////
当有人按下创建人员按钮时,如何创建人员类的实例。我不想将类的实例命名为像 person_1 这样的通用名称,而是希望实例的名称是顶部文本框中的文本。我已阅读有关 Activator.CreateInstance 的 MSDN 文章,并确定这是实现此目的的最佳方法。但是我不知道如何正确超载它。我需要能够将类的实例作为人名而不是 obj 引用。

简单是这里的目标。

【问题讨论】:

  • 您不能动态设置实例名称。为什么实例名称对您如此重要???
  • 如果每次按下按钮,实例都会被覆盖,我还能如何区分对象。
  • 我想理解你的意思,你想创建一个 Person 实例并将它的 name 字段设置为 textBox1.text 吗?
  • 这正是我的意思,我只是不知道如何正确表达它

标签: c# winforms class oop activator


【解决方案1】:

如果您希望维护所有创建的“人员”,您需要将它们粘贴在某种形式的容器中。在您的表单类中放置一个字段,如下所示。

私有列表_persons = new List();

然后,当您处理按钮单击时,您可以将动态创建的人员添加到此集合中。鉴于您没有提供太多关于您要完成的任务的背景信息,所以这个问题有点棘手。

_persons.add(Activator.CreateInstance());

【讨论】:

    【解决方案2】:

    我从您的描述中了解到,您想要存储每个创建的人。正如你所说,你不能将它存储在 person1 中。

    您应该有一个已创建人员的列表并将其存储在其中。不用Activator.CreateInstance()

    List<Person> CreatedPersons = new List<Person>();
    
    private void createPersonBox_Click(object sender, EventArgs e)
    {
        var tempPerson = new Person(); //No need to use Activator.CreateInstance<Person>();
        // Fill the tempPerson with form text boxes.
    
        createdPersons.Add(tempPerson);
    }
    

    Activator.CreateInstance 对于其他一些场景很有用,这些场景创建对象的类型不固定,您希望将其作为参数传递。例如,在以下示例中,您要创建type 的实例:

    Type type;
    type = GetCreatingType(); // Some algorithm to find out what type to create;
    
    var instance = new type(); // This doesn't work
    var instance = Activator.CreateInstance(type); // But this works.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-14
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多