将对象传递到不同的Windows窗体 [英] Passing object to different windows forms
问题描述
我想在获胜表格之间传递C#对象。目前,我已经建立了一个基础项目来学习如何执行此任务,该项目由两种形式组成:form1和form2,以及一个名为class1.cs的类,该类包含get和set方法,用于设置在form1中输入值的字符串变量。 (应该从表格2中获取存储在class1对象中的值)
I want to pass a C# object between win forms. At the moment, I have setup a basic project to learn how to do this which consists of two forms - form1 and form2 and a class called class1.cs which contains get and set methods to set a string variable with a value entered in form1. (Form 2 is supposed to get the value stored in the class1 object)
如何从在form1中设置的对象中获取字符串值?我是否需要将其作为参数传递给form2?
How can I get the string value from the object that was set in form1? Do I need to pass it as a parameter to form2?
任何评论/帮助都会被赞赏!
Any comments/help will be appeciated!
谢谢,
编辑:这是我目前的代码:(form1.cs)
Here's the code I have at the moment: (form1.cs)
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
Class1 class1 = new Class1();
class1.setStringValue(textBox1.Text);
}
}
}
}
推荐答案
有几种不同的方法可以执行此操作,可以使用静态类对象,上面的示例非常适合此活动。 p>
There are a few different ways to do this, you could use a static class object, the above example would be ideal for this activity.
public static class MyStaticClass
{
public static string MyStringMessage {get;set;}
}
您无需实例化该类,只需调用它即可。
You don't need to instance the class, just call it
MyStaticClass.MyStringMessage = "Hello World";
Console.WriteLine (MyStaticClass.MyStringMessage);
如果需要对象的实例,可以将在Form1上创建的类对象传递给Form2
If you want an instance of the object you can pass the class object that you create on Form1 into Form2 with the following.
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.MyClass = class1;
form2.Show();
}
然后在Form2上创建一个属性以接受类对象。
Then create a property on Form2 to accept the class object.
public Class1 MyClass {get;set;}
记住使Class1对象成为全局变量,而不是在按钮2本身中创建它。
remember to make the Class1 object a global variable rather than create it within button 2 itself.
这篇关于将对象传递到不同的Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!