不同窗口形式的类的C#对象 [英] C# object of class in different windows form
问题描述
如果我运行我的项目,我会看到这个窗口:
If I run my project I get this window:
然后我按下按钮auto hinzufügen == 添加汽车.方法代码如下:
Then I press the button auto hinzufügen == add car. Here the code of the method:
private void button1_Click(object sender, EventArgs e)
{
addCarcs window = new addCarcs();
window.Show();
}
现在第二个窗口打开:
我填写了两个字段并按下按钮auto hinzufügen == 添加汽车.然后我创建一个 car 类的新对象.代码如下:
I fill both fields and press the button auto hinzufügen == add car. Then I create a new object of the class car. Here the code:
private void button1_Click(object sender, EventArgs e)
{
if((kennzeichen.Text != "") && (automarke.Text != ""))
{
car myCar = new car();
myCar.addCar(kennzeichen.Text, automarke.Text);
this.Close();
}
}
这是car类的代码:
class car
{
public car()
{
this.carMark = "";
this.carMark = "";
}
public void addCar(string carMark, string carBrand)
{
this.carMark = carMark;
this.carBrand = carBrand;
carNumber++;
}
public string showCar()
{
return string.Format(
"Automarke: {0} --- Autokennzeichen {1}", this.carBrand, this.carMark);
}
private string carMark;
private string carBrand;
static int carNumber;
}
现在我再次来到主窗口:
Now I come to the main Window again:
现在我按下第二个按钮auto anzeigen == show car.我想显示添加的汽车,但是如果我在按钮方法中编写此代码:
Now I press the second button auto anzeigen == show car. I want to show the added car, but if I write this code in the button method:
private void showCar_Click(object sender, EventArgs e)
{
myCar.showCar();
}
我收到一个错误:
如何在不同的表单之间发送一个类的创建对象?
How can I send the created object's of a class between different forms?
推荐答案
您需要创建一个属性 Car MyCar { get;set;}' 在类级别.在构造函数中设置它的值,如
MyCar = new Car()并在需要 Car 对象的任何地方访问
MyCar`.
You need to create a Property Car MyCar { get;set; }' at the class level. Set its value in the constructor like
MyCar = new Car()and access the
MyCar` everywhere you need the Car object.
这篇关于不同窗口形式的类的C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!