簡體   English   中英

如何將返回的變量從一個類存儲到另一個類變量?

[英]How to Store the returned variable from one class to another class variable?

Form1.cs的

public String Return_inf()
{
    names = U_name.Text;
    return names;   
}

我嘗試將其存儲在另一個類字符串變量中,例如:

public string  CheckLogin()
{
     Form1 f = new Form1();
     string name=f.Return_inf();
 }  

但是變量是空的....

變量名為空的原因是因為您正在CheckLogin()方法中創建一個全新的Form1對象,而不是使用現有的Form1對象。

您可以讓您的班級互相引用。

這是一個示例,您可以嘗試使表單相互引用

Form1類別:

public class Form1 : Form
{
    // Class variable to have a reference to Form2
    private Form2 form2;

    // Constructor
    public Form1()
    {
        // InitializeComponent is a default method created for you to intialize all the controls on your form.
        InitializeComponent();

        form2 = new Form2(this);
    }

    public String Return_inf()
    {
        names = U_name.Text;
        return names;
    }
}

Form2類:

public class Form2 : Form
{
    // Class variable to have a reference back to Form1
    private Form1 form1;

    public Form2(Form1 form1)
    {
        InitializeComponent();
        this.form1 = form1;
    }

    public string CheckLogin()
    {
        // There is no need to create a Form1 object here in the method, because this class already knows about Form1 from the constructor
        string name=form1.Return_inf();

        // Use name how you would like
    }  
}

還有其他方法可以執行此操作,但是IMO這是在兩種形式之間共享數據的基礎。

您可以通過定義靜態類來做到這一點

static class GlobalClass
{
    private static string U_name= "";

    public static string U_name
    {
        get { return U_name; }
        set { U_name= value; }
    }
}

您可以按照以下方式使用它

GlobalClass.U_name="any thing";

然后像這樣回憶

string name=GlobalClass.U_name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM