全局对象声明 [英] global object declaration

查看:120
本文介绍了全局对象声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我需要找出如何声明一个可以从同一应用程序的所有函数访问的全局对象.

我创建了一个全局的串行端口对象:

hi all,

i need to find out how i can declare a global object which can be accesible from all functions of the same application.

i created a global serialport object :

System::IO::Ports::SerialPort^ serialPort = gcnew SerialPort(L"COM4" , 300, Parity::Even , 7, StopBits::One);



然后,当尝试运行该应用程序时,我会看到以下内容:

错误C3145:"serialPort":全局或静态变量可能没有托管类型"System :: IO :: Ports :: SerialPort ^"

等待您的解决方案,

thanx



then, when try to run the application i see this:

error C3145: ''serialPort'' : global or static variable may not have managed type ''System::IO::Ports::SerialPort ^''

waiting your solutions,

thanx

推荐答案

.NET没有全局对象的概念(最后,谢天谢地!).相反,您可以具有某些托管的"ref"类或结构的静态成员.

正式地,这解决了您的问题.但是,即使这还不够好,也可能是编码风格不良的征兆.

有两种纠正方法.第一个是最可取的,也是最通常适用的:将serialPort用作类的局部变量或实例(非静态)成员,以声明运行所显示代码的方法.通常,这已经足够了.考虑使用对该对象的引用.应用程序的许多其他部分确实不太需要使用它.最有可能的情况恰好相反:您需要在有限的范围内使用此对象,它越小越好.

在极少数情况下,当您确实确实需要全局使用某些东西时,正确的设计模式单人模式.请参阅:
http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 [ ^ ],
http://en.wikipedia.org/wiki/Singleton_pattern [ http://csharpindepth.com/Articles/General/Singleton.aspx [
.NET does not have a concept of global objects (finally, thanks goodness!). Instead, you can have a static member of some managed "ref" class or structure.

Formally, this solves your problem. But even this is not good enough, would be the sign of bad coding style.

There are two ways of putting it right. First one is the most desirable and most usually applicable: make your serialPort a local variable or an instance (non-static) member of the class declaring the method running the code you show. Usually, this is quite enough. Think about using of the reference to this object. It is very unlikely it is really needed to be used by many other parts of your application. Most likely, the situation is directly the opposite: you need to use this object in some limited scope, the smaller, the better.

In rare cases when you really need to use something globally, the right design pattern is the singleton pattern. Please see:
http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29[^],
http://en.wikipedia.org/wiki/Singleton_pattern[^].

The singleton pattern itself can be implemented in a good or a bad way. This is a sample of good .NET implementation:
http://csharpindepth.com/Articles/General/Singleton.aspx[^].

Sorry, this is C#, but I don''t think it could be a problem for you. This is still .NET, and you are using C++/CLI which is in few ways more advanced then C#.

But let me repeat: I believe in your case you only need a very local use of the object in question.

—SA


这篇关于全局对象声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆