简体   繁体   中英

how to declare an object that can be used in Other events?

I am working on a windows form. I am creating an object called client and the client has many functions including login() search(). the login function is called when I click the "login button" and the search function is called when I click on the "search button"

I was able to accomplish to create a "global object"( for a lack of a better term) by declaring it here:

namespace WindowsFormsApplication1
{

public partial class Form1 : Form
{
    MyClient client = new MyClient();

 private void btnLogIn_Click(object sender, EventArgs e)
    {
       client.login()
 private void btnSearch_Click(object sender, EventArgs e)
    {
       client.search()

Now, the problem I face is that sometimes the client disconnects and I have to use another object to relogin, I cannot use the same object.

I am thinking about having a button to relogin, create a new object, and keep using the same name "client" for the object on the other events.

Any thoughts?

You can wrap your client variable in a property or method, which encapsulates logic to determine if you need to reconnect. Suppose you had a method in client called wasDisconnected() which does this. You could "lazy-load" the class-level variable like such.

public partial class Form1
{
    MyClient _client;

    protected MyClient client
    {
        get
        {
            // Check if we need to reconnect.
            if (_client == null || client.wasDisconnected())
                _client = new MyClient();
            return _client;
        }
    }

    // ...
}

Your click methods in this case would remain unchanged, but they would now access the MyClient instance through the property instead of directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM