开发者

using object in multiple function

开发者 https://www.devze.com 2023-01-01 17:55 出处:网络
How can i use object from one function in another ? main() { private void button1_click { MyClass object = new MyClass();

How can i use object from one function in another ?

main()
{
  private void button1_click { 

  MyClass object = new MyClass();
  object.blabla();

  }

  private void button2_clic开发者_运维百科k {

  // how can i use object from button1_click ??

  }
}


By storing the object out of the scope of a function.

main()
{
  MyClass obj;

  private void button1_click 
  { 
    obj = new MyClass();
    obj.blabla();
  }

  private void button2_click 
  {
    //maybe check for null etc
    obj.dosomethingelse();
  }
}


basically this is a more fundamental question, which can be solved as eg

class program
{
    void Main(string[] args)
    {
      private MyClass FooInstance;
      private void button1_click()
      {
        // TODO be defensive: check if this.FooInstance is assigned before, to not override it!
        this.FooInstance = new MyClass();
        this.FooInstance.blablabla();
      }

      private void button2_click()
      {
        // TODO add some null check aka make sure, that button1_click() happened before and this.FooInstance is assigned
        this.FooInstance = ....;
      }
    }
}

you may also choose lazy-loading as an option (mentioned by Andrew Anderson)


make object as member variable of the class where functions are defined.

main()
{
  private MyClass object;

  private void button1_click { 

  object = new MyClass();
0

精彩评论

暂无评论...
验证码 换一张
取 消