[英]how to declare an object that can be used in Other events?
I am working on a windows form. 我正在Windows窗体上工作。 I am creating an object called client and the client has many functions including login() search(). 我正在创建一个名为client的对象,该客户端具有许多功能,包括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. 我正在考虑使用一个按钮来重新登录,创建一个新对象,并在其他事件上为该对象继续使用相同的名称“ client”。
Any thoughts? 有什么想法吗?
You can wrap your client
variable in a property or method, which encapsulates logic to determine if you need to reconnect. 您可以将client
变量包装在属性或方法中,该属性或方法封装逻辑以确定是否需要重新连接。 Suppose you had a method in client called wasDisconnected()
which does this. 假设您在客户端中有一个名为wasDisconnected()
可以执行此操作。 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. 在这种情况下,您的click
方法将保持不变,但是现在它们将通过该属性而不是直接访问MyClient实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.