简体   繁体   English

从Form1将值设置为Class1中的属性,然后使用C#Windows Form将Class1中的该属性的值获取到Form2

[英]Set value into a property in Class1 from Form1 then get value of that property in Class1 to Form2 using C# Windows Form

I have this problem, i've set a value to a property from shall we say Form1, then get that value in Form2 but it return null. 我有这个问题,我已经从Form1中设置了一个属性值,然后在Form2中获得了该值,但它返回了null。

sample code. 示例代码。

//Sample.cs
public class Sample
{
    private string exchange;

    public Sample()
    {
    }

    public string Exchange
    {
        get { return exchange; }
        set { exchange = value; }
    }
}

//From Form1 set value
private void setBtn_Click_1(object sender, EventArgs e)
{
    Sample testing = new Sample();

    testing.Exchange = exchange.Text;
}

//From Form2 get value
private void getBtn_Click_1(object sender, EventArgs e)
{
    Sample testing2 = new Sample();
    string exchange2 = testing2.Exchange;
}

Here's the problem, exchange2 have a value of null, i know its because i declared a new instance, please tell me how to get the value using Form2 that have been set in Form1. 这里的问题是,exchange2的值为null,我知道它是因为我声明了一个新实例,请告诉我如何使用在Form1中设置的Form2获取值。

Thanks in advance guys! 在此先感谢大家!

It is OK return null because you each time create a new object 可以返回null,因为每次创建一个新对象

Sample testing2 = new Sample();

declare the public property in Form2 class 在Form2类中声明公共财产

  class Form2
  {
     public Sample MySample {get; set;}
  }
private void setBtn_Click_1(object sender, EventArgs e)
{
Sample testing = new Sample();

Form2 form2 = new Form2();
form2.MySample = testing;
form2.Show();
}

If you want to use classes and properties in this way make exchange field static so it will be shared among all instances of your class. 如果要以这种方式使用类和属性,请将交换字段设置为静态,这样它将在您的类的所有实例之间共享。 Static fields are class related and not instances related and in your case from Form1 and Form2 you are creating different instances of class. 静态字段与类相关,与实例无关,在Form1和Form2中,您要创建不同的类实例。

Following are few posibilites: 以下是几种可能性:

1) Delcare the property static: 1)Delcare的属性静态:

public static string Exchange{get;set;}

2) Pass the object created in Form1 in some way to Form2: 2)以某种方式将在Form1中创建的对象传递给Form2:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM