不同窗口形式的类的C#对象 [英] C# object of class in different windows form

查看:23
本文介绍了不同窗口形式的类的C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行我的项目,我会看到这个窗口:

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 likeMyCar = new Car()and access theMyCar` everywhere you need the Car object.

这篇关于不同窗口形式的类的C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆