在C#中从构造函数创建新对象

时间:2019-01-16 13:02:43

标签: c# constructor

我是C#的新手。我正在尝试从另一个类的构造函数创建一个新对象。

namespace ClientsCatalgoWindowsForms
{
    public partial class GeneralForm : Form
    {
        public GeneralForm(string ClientName)
        {
            string FormName = ClientName;

           // Client CurrClient = new Client(FormName);
            Client CurrClient = new Client();
            InitializeComponent();


        //ClientForm(ClientName);
        }

        private void OkButton_Click(object sender, EventArgs e)
        {
            //CreateBatch(true);



            CreateObjectsArray();

            CreateControlArray(false);

            //CreateBatch(0);

            Application.Exit();
        }

我尝试创建名称为Client的类型为CurrClient的新对象。

当我尝试在“类”方法之一中使用它时,他们无法识别新对象。我在做什么错了?

新的对象类出现在另一个cs文件中。有关系吗?

3 个答案:

答案 0 :(得分:1)

您需要在类级别声明currClient变量,然后在构造函数中对其进行初始化。之后,您应该可以在其他方法中使用currClient。

 data_stores_total= data_stores.groupby(['store'], as_index=False).agg({'mean': 'item1':, 'sum': ['item2', 'item3']})

答案 1 :(得分:0)

该对象的引用范围是 GeneralForm 构造函数,请尝试以下操作,希望对您有所帮助。

 public partial class GeneralForm : Form
{
    public Client CurrClient;

    public GeneralForm(string ClientName)
    {
        string FormName = ClientName;
        CurrClient = new Client();
        InitializeComponent();
    }

}

答案 2 :(得分:0)

构造函数只是在实例化“类”时在内部调用的函数(方法)。 它包含在对象创建期间必须执行的代码。 它的主要用途是为类中存在的变量(成员)赋值。

      class Sample
{   
  .......
  // Constructor
  public Sample() {}
  .......
}

// an object is created of the  Sample class,
// So above constructor is called
Sample obj = new Sample(); 
相关问题