使对象全局化 [英] Make an object global
问题描述
我试图定期从通过USB线连接的设备读取并使用更新的信息更新WinForm属性。该设备是由TinkerForge制造的GPS,具有与之关联的API。访问设备有两个步骤:
首先连接到设备,代码是:
I am trying to periodically read from a device connected via a USB cable and update WinForm properties with the updated information. The device is a GPS made by TinkerForge that has an API associated with it. There are two steps to access the device:
First connect to the device, the code is:
IPConnection ipcon = new IPConnection();
Bricklet gps - new BrickletGPS(UID, icon); Where UID is a sting with the
device ID
ipcon.Connect (HOST, PORT); Where HOST is "localhost" and PORT is 4223;
连接后有用于检索数据的gps中的一些方法,例如:
Once connected there are a number of methods in gps for retrieving data such as:
gps.GetDateTime (out long date, out long time);
我想在全球范围内提供GPS,所以一旦连接,我可以继续定期访问设备。
结构代码是:
I would like to make gps available globally so once connected I can continue to access the device periodically.
the structure of the code is:
public partial class Form1:form
{
public Form1()
{
InitializeComponent();
Timer code in here to call DoWork periodically to collect GPS Data
Will use RunWorkerCompleted to update the GUI with the new Data
}
private void DoWork (Object sender, DoWorkEventArgs e)
{
I can put the connection and access code in here and it works
but then the
connection is reestablished on each cycle. I'd like access to
the gps object here rather then continually reinitializing it.
}
{
我的尝试:
当我将初始化代码放在公共Form1()之前时
What I have tried:
When I put the initialization code before public Form1() the
IPConnection ipcon = new IPConection(); works
但是下一个语句Bricket gps = new BrickletGPS(UID,ipcon)被标记为错误,即字段初始化程序无法引用非静态字段方法或属性Form1( ).ipcon。因此初始化失败。
当我在Form1()方法中进行初始化时,然后语句如
gps.GetDateTime表示当前上下文中不存在gps。同样的事情发生在我第一次使用if语句来执行连接。在if语句字段之外无法识别gps对象。
我是C#和.net的新手,我不确定是否可能,如果是,那么谁来让gps对象全局化
感谢您的帮助
However the next statement Bricket gps = new BrickletGPS (UID, ipcon) is flagged with the error that a field initializer cannot reference the non static field method or property Form1().ipcon. As a result the initialization fails.
When I put the initialization in the Form1() method then statements like
gps.GetDateTime indicate that gps does not exist in the current context. The same thing happens is I put a first time if statement to execute the connection. The gps object is not recognized outside the if statement field.
I'm new to C# and .net and am not sure if it is possible and if so who to make the gps object global
Thanks for any help
推荐答案
如果您需要访问单个对象从多种形式,一种方法是创建一个静态类来保存和初始化对象。类似
If you need to access the single object from multiple forms, one way is to create a static class to hold and initialize the object. Something like
public static class Gps {
public IPConnection Connection { get; private set; }
public Initialize() {
Gps.Connection = new new IPConection();
}
}
现在你可以参考程序中的静态类,比如
Now you can refer the static class everywhere in your program like
Gps.Initialize();
...
Gps.IPConnection...
这篇关于使对象全局化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!