开发者

What is the correct way of stopping an object in a method that was created in another?

I have a form that has a button which creates a new object and calls it's start() method.

The program works fine, however, I now want to create a stop button. I obviously cannot call the object's stop() method as it is elsewhere, but, I just can't think of the correct way of changing my code.

As I write this, the best thing I can think of is to take the MyObject myo = new MyObject("test"); and place MyObject myo; at the top of the class, outside methods and then try to set it from within the class.

What woul开发者_StackOverflow中文版d you do in this situation?


It's all dependent on scope.

If you want the form, at any time, to have visibility to that object, placing it as a private/protected member within the form's object is probably a good route. (make sure it's not null though.

class MyForm
{
   private MyObject myobject;

   private MyForm(){
     // create the object
     myobject = new MyObject;
   }

   private void Start_Click(){
     myobject.start();
   }
   private void Stop_Click(){
     myobject.stop();
   }
 }

If this object is constantly referenced, you could follow a singleton pattern.

If this is something you can re-create based on [an/the] argument(s) passed to the construct, you can re-create it every time it's needed.


That is is exactly what you are supposed to do. Its called creating a member variable.

But make sure you don't call myo.stop() when myo is null!


You are correct. You have to store the object reference some place so that you can call its "stop" method later.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜