Use of one class object in another class?

2019-03-07 03:14发布

问题:

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.