如何在button1中实例化类obj并在button2中使用obj方法 [英] How do I instantiate class obj in button1 and use the obj method in button2

查看:83
本文介绍了如何在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 变量并使其在整个页面中变得通用



Declare the Cat variable outside the event and make it common across the page

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();
       }


当您编写类似的代码时,您不能。您的代码将 kitty 声明为局部变量 - 这意味着它是在堆栈上创建的,并从中分配了一个新的 cat 实例堆。当 button1_Click 事件处理程序方法退出时,该变量会自动销毁,并且不再有对基于堆的对象的引用: kitty 在方法结束时超出范围

因为任何变量的范围仅限于包含它的大括号(除了类外)具有适当属性的级别变量: public protected 等)它们不能在大括号块之外访问:

When you write code like that, you can't. Your code declares kitty as a local variable - which means it is created on the stack and assigned a new cat instance from the heap. When the button1_Click event handler method exits, the variable is automatically destroyed, and there are no more references to the heap based object: kitty goes out of scope at the end of the method.
Since the scope of any variable is limited to the curly brackets that enclose it (With the exception of class level variables with the appropriate attributes: public, protected, etc.) they cannot be accessed outside that curly bracket block:
{
   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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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