如何在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;