Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中使用从一个方法到另一个方法的变量值?_C# - Fatal编程技术网

如何在C#中使用从一个方法到另一个方法的变量值?

如何在C#中使用从一个方法到另一个方法的变量值?,c#,C#,在我的代码中,我使用了两种单击按钮的方法。我想使用另一个方法中第一个方法的一些变量的值。例如:我想使用button1\u单击button2\u单击中定义的h和w的值。可能吗 public int h, w; public Form1() { InitializeComponent(); textBox1.Text = "Image Path here ..."; } public void button1_Click(object sender, EventArgs e) {

在我的代码中,我使用了两种单击按钮的方法。我想使用另一个方法中第一个方法的一些变量的值。例如:我想使用
button1\u单击
button2\u单击
中定义的
h
w
的值。可能吗

public int h, w;
public Form1()
{
    InitializeComponent();

    textBox1.Text = "Image Path here ...";
}

public void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Select an Image";
    dlg.Filter = "jpg files (*.jpg)|*.jpg";
    if (DialogResult.OK == dlg.ShowDialog())
    {
        this.pictureBox1.Image = new Bitmap(dlg.FileName);
        Bitmap img = new Bitmap(dlg.FileName);
        int w = img.Width;
        int h = img.Height;
        pictureBox1.Height = h;
        pictureBox1.Width = w;
        textBox1.Text = dlg.FileName;
    }
}

public void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show("Height is- " + h.ToString() + " Width is- " + w.ToString(), "Height & Width");
}

在您的
按钮1u中单击
,您没有分配给类的
h
w
,而是分配给局部变量。换衣服

 int w = img.Width;
 int h = img.Height;


如果我正确理解了您想要实现的目标,它应该会起作用。

您应该学会编写可维护的代码(例如,
textbox1
不是很有描述性)。。。并删除无用的代码,如创建
位图两次。您还应该使用
String.Format
设置文本格式。并正确缩进文本。您应该设置消息框标题和图标。
 w = img.Width;
 h = img.Height;