本文介绍了如何在button1中实例化类obj并在button2中使用obj方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void button1_Click(object sender, EventArgs e)
{
Cat kitty = new Cat();
}
private void button2_Click(object sender, EventArgs e)
{
//kitty.eat();
}
如何通过button2访问kitty.eat()?
现在kitty在当前情况下不退出。
谢谢。
我尝试了什么:
how to access kitty.eat() by button2?
now kitty is not exit in the current context.
thank you.
What I have tried:
private Cat button1_Click(object sender, EventArgs e)
或由EventArgs完成?
or done by EventArgs ?
推荐答案
Cat kitty; // declare outside
private void button1_Click(object sender, EventArgs e)
{
kitty = new Cat();
}
private void button2_Click(object sender, EventArgs e)
{
if (kitty != null) // validate for null value.
kitty.eat();
}
{
int a = 1;
if (a == 1)
{
int b = 2;
} // b goes out of scope here
a = b; // Illegal: b is not in scope and is not available
} // a goes out of scope here
要分享 两个处理程序之间的变量,将定义移到任何方法之外:
To "share" the variable between the two handlers, move the definition outside any method:
private Cat kitty = null;
private void button1_Click(object sender, EventArgs e)
{
kitty = new Cat();
}
private void button2_Click(object sender, EventArgs e)
{
kitty.eat();
}
这篇关于如何在button1中实例化类obj并在button2中使用obj方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!