referencing other class methods without creating a new instance
I have a class by itself called clientChat
that does basic network stuff. I have several other classes linked to different window forms. In my first form I have a variable referenced to the chat class like so:
clientChat cc = new clientChat();
Everything works okay their, the class has been initialized and everything is in motion. After the first forms is done performing it's duty I bring up my second form that's obviously linked to a new class file.
Now my question is, how can I reference what's going on in the clientChat
class without setting a new instance of the class? I need to pass data from the form to the networkstream
and if I create a new instance of the class wouldn't that require a new connection to the server and basically requ开发者_Python百科ire everything to start over since it's "new"? I'm a bit confused and any help would be great, thanks. C# on .NET4.0
You could create an instance of clientChat
in the beginning of your program and then, simply pass its reference to the classes that need it.
You may want to look into the Singleton design pattern. Mr Skeet has written a good article on how to implement it in C# here. (Just use version 4. its the easiest and works fine =) )
Presumably you would either:
- Create the object from the code that creates and shows both forms, and pass a reference to that same instance to both forms, or:
- If you create the second form from inside the first form, pass a reference to the instance referenced by the first form to the second somehow (via a property or a constructor, for example).
In additional to @Jens's answer, there are 5 approaches on the linked page, while I think we have the 6th using Lazy<T>
in C# 4.0
public sealed class Singleton
{
private Singleton() { }
private static readonly Lazy<Singleton> m_instance = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return m_instance.Value;
}
}
}
精彩评论