[英]C# Creating new instance of class from another form
I'm completely new to object orientated programming in C# and was wondering what the best way of using a 2nd form to enter details that are used to create a new instance of an object that exists on the first form. 我对使用C#进行面向对象的编程完全陌生,并且想知道使用第二种形式输入细节的最佳方法是什么,该细节用于创建第一种形式上存在的对象的新实例。
Do I just pass the variables back to the form and create the new instance on the new form. 我是否只是将变量传递回表单并在新表单上创建新实例。 Just wondering the best way....
只是想知道最好的方法。
Basic code for form1 Form1的基本代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.ShowDialog();
}
}
class person
{
public string Name { get; set; }
public int age { get; set; }
}
Basic code for Form2 Form2的基本代码
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// How do I create a new instance of person using these variables
string name = "Neil";
int age = 42;
this.Close();
}
}
Any help greatly Appreciated 任何帮助大加赞赏
In Form2 class, 在Form2类中,
First include namespace where the Person
class is present Then using new
keyword you can create instance of person class 首先包括存在
Person
类的名称空间,然后使用new
关键字创建person类的实例
Person personObj = new Person();
If you want to assign values to the properties present in Person class, then 如果要为Person类中存在的属性分配值,则
Person personObj = new Person()
{
Name = "Nail",
Age = 23
};
You can create an object in Form2 and get it in Form1 like this: 您可以在Form2中创建一个对象,然后像这样在Form1中获取它:
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
if (frm2.ShowDialog() == DialogResult.OK)
{
var p = frm2.Person;
}
}
}
public partial class Form2 : Form
{
public person Person { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Person = new Person();
//set properties in Person object
}
}
Or if you want to pass object from Form1 to Form2, update it in Form2 and retake it Form1, you can do like this: 或者,如果要将对象从Form1传递到Form2,在Form2中对其进行更新并重新获取Form1,则可以执行以下操作:
public partial class Form1 : Form
{
private void button1_Form1_Click(object sender, EventArgs e)
{
var p = new Person();
Form2 frm2 = new Form2(p);
if (frm2.ShowDialog() == DialogResult.OK)
{
var updatedPerson = frm2.Person;
}
}
}
public partial class Form2 : Form
{
public person Person { get; set; }
public Form2(Person p)
{
this.Person = p;
InitializeComponent();
}
private void button1_Form2_Click(object sender, EventArgs e)
{
//set properties of this.Person
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.