Use of one class object in another class?

ε祈祈猫儿з 提交于 2019-12-20 07:58:10

问题


i am making applications in c#.In that application i have one class as DataCapture.cs. In same application i have another class as Listner.cs . Here in Listner.cs class i want to use object of DataCapture.cs without creating new object of DataCapture.cs. As if i am creating new object of DataCapture.cs,i cant access the the data DataCapture.cs as it creates the new instance of class and all data gets lost as i am using collection in DataCapture.cs.Please help me.Thanks in advance.


回答1:


You vould use the the singleton pattern to ensure that only one object of the class exists. You could then get the object as,

DataCapture.Instance. ...... where .Inastance is public static.




回答2:


if I clear understand what you'e asking for, you can do somethign like this.

//somewhere in the code you create 
DataCapture dataCapture = new DataCapture(); 

And, considering that Listener needs actually DataCapture

public class Listener {

  DataCapture _dataCapture = null; 

  public Listener(DataCapture dc) {
    _dataCapture = dc;
  }

  /* Use _dataCapture member inside listener class member functions. 
     One instance of DataCapture class, shared inside Listener.
  */
}

If this is not what you're asking for, please clatify your question.




回答3:


you can pass a reference of already created DataCapture's object to the Listener class. For instance pass the instance to the Listener's constructor.

class Listener{
  Listener(DataCapture data)
  {
     this.data = data;
  }
}

Now within Listener you have access to DataCapture instance.



来源:https://stackoverflow.com/questions/8572206/use-of-one-class-object-in-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!