C# “全球”;“类对象”;或全球;“服务器对象”;
我正在做一个项目,包括一个定制的OPC客户端。 Main类表示WPF应用程序中的MainWindow。 专用字段C# “全球”;“类对象”;或全球;“服务器对象”;,c#,C#,我正在做一个项目,包括一个定制的OPC客户端。 Main类表示WPF应用程序中的MainWindow。 专用字段\u opcServer将保存一个对象以供进一步使用。 任何时候都只允许一个\u opcServer对象。 我想出了这个(都是示例代码,效果很好) 代码中没有太多注释,但我想你明白了。 每次通过用户操作触发连接或断开连接时,都会创建一个新的OPC客户端对象,并向一个或另一个方向传递服务器对象。 像这样的方法会更多(比如读标签等等),但是由于用户每天只应该使用一到两次,我认为创建新对象和
\u opcServer
将保存一个对象以供进一步使用。
任何时候都只允许一个\u opcServer
对象。
我想出了这个(都是示例代码,效果很好)
代码中没有太多注释,但我想你明白了。
每次通过用户操作触发连接或断开连接时,都会创建一个新的OPC客户端对象,并向一个或另一个方向传递服务器对象。
像这样的方法会更多(比如读标签等等),但是由于用户每天只应该使用一到两次,我认为创建新对象和在它们之间传递一些东西没有问题
但是,如果有一个真正有趣的用户认为他必须一直使用这些东西(连接/断开连接/等等),该怎么办呢。然后我将创建许多对象
我想了想,想出了这个
public class Main
{
// the client object
private OpcClient _opcClient = OpcClient.Instance;
public Main(){}
private void connectOpcServer()
{
if(this._opcClient.connectOpcServer("someOpcServer"))
{
// we made the connection and can now use
// this._opcClient.opcServer
}
else
{
// connection failed
}
}
private void disconnectOpcServer()
{
if(this._opcClient.disconnect())
{
// disconnected
}
else
{
// something went wrong
}
}
}
public class OpcClient
{
private static OpcClient _instance;
public static OpcClient Instance
{
get
{
if(instance == null)
{
_instance = new OpcClient();
}
return _instance;
}
}
private OpcClient()
{
this.opcServer = new OpcServer();
}
public OpcServer opcServer
{
get;
private set;
}
public bool connectOpcServer(string progID)
{
return this.opcServer.Connect(progID);
}
public bool disconnectOpcServer()
{
return this.opcServer.disconnect();
}
}
现在,我创建一个OPC客户机的Singleton,并将其传递给主类。现在只创建一个对象,用户可以全天单击连接/断开连接
在这里最好的方法是什么
我选择第二个选项。 通过选择单例方法,我可以确保只有一个服务器对象。 这是非常重要的
public class Main
{
// the client object
private OpcClient _opcClient = OpcClient.Instance;
public Main(){}
private void connectOpcServer()
{
if(this._opcClient.connectOpcServer("someOpcServer"))
{
// we made the connection and can now use
// this._opcClient.opcServer
}
else
{
// connection failed
}
}
private void disconnectOpcServer()
{
if(this._opcClient.disconnect())
{
// disconnected
}
else
{
// something went wrong
}
}
}
public class OpcClient
{
private static OpcClient _instance;
public static OpcClient Instance
{
get
{
if(instance == null)
{
_instance = new OpcClient();
}
return _instance;
}
}
private OpcClient()
{
this.opcServer = new OpcServer();
}
public OpcServer opcServer
{
get;
private set;
}
public bool connectOpcServer(string progID)
{
return this.opcServer.Connect(progID);
}
public bool disconnectOpcServer()
{
return this.opcServer.disconnect();
}
}