从不同类访问变量 [英] Access Variable From Different Class

查看:48
本文介绍了从不同类访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将tboxValue的值传递给我的方法EE? 它总是打印0?

How do I pass the value of tboxValue to my method EE?  It always prints 0?

public partial class Form1 : Form
{

    public double tboxvalue;
    private string exportdata;

    public Form1()
    {
        InitializeComponent();
    }

    private void btnClicker_Click(object sender, EventArgs e)
    {
        Functions.EE();
    }
    private void txtData_CheckedChanged(object sender, EventArgs e)
    {
        bool @checked = ((CheckBox)sender).Checked;

        if (@checked.ToString() == "True")
        {
            exportdata = "Yes";
            tboxvalue = Convert.ToDouble(this.txtData.Text);
            System.Diagnostics.Debug.WriteLine(tboxvalue.ToString());
        }
        else
            exportdata = "No";
    }
}
class Functions
{
    public static void EE()
    {
        Form1 f1 = new Form1();
        System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
    }
}

推荐答案

新建你正在创建一个新实例。 tboxvalue的值为0,因为对于新实例它为0。您更改了调用EE的实例的tbox值。

with new you are creating a new instance. The value of tboxvalue is 0 because it' 0 for a new instance. You changed tboxvalue of the instance calling EE.

    public static void EE(Form1 f1)
    {
        System.Diagnostics.Debug.WriteLine(f1.tboxvalue.ToString());
    }


    private void btnClicker_Click(object sender, EventArgs e)
    {
        Functions.EE(this);
    }

您必须将正确的实例传递给静态方法,而不是创建一个新的

You have to pass the correct instance to the static method instead of creating a new one.

问候,Chris


这篇关于从不同类访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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