2015-10-05 67 views
-1

我正在使用全局类来设置其中的一些信息。我想填写这个班级的名单。将文本添加到全局类中的静态列表中

我想这一点:

#pragma once 
#include "Element.h" 
#include "PLCconnection.h" 

ref class ManagedGlobals { 
public: 
    static List<Element^>^ G_elementList; //wordt gedefineerd in ReadPlotFile.cpp 
    static System::String^ G_plotFileName; //wordt gedefineerd in PlotFileForm.h 
    static System::String^ G_Language;  //wordt gedefineerd in MainForm.h 

    static PLCconnection^ G_PLCverbinding = gcnew PLCconnection(); 
    static bool G_plcOnline = G_PLCverbinding->ConnectToPLC(); 

    static List<System::String^>^ G_VariableList = gcnew List<System::String^>; 
    //static List<System::String^>^ G_VariableList = gcnew List <System::String^>; 
    G_VariableList = G_PLCverbinding->LeesTest2(); // this line gives the error 
}; 

错误,我得到:this declaration has no storage class or type specifier

我该如何解决这个问题?我在我的项目的多个地方使用这个列表,所以我需要它是全球性的。

回答

0

您必须声明G_VariableList成员在一个单一的表达,如下:

static List<System::String^>^ G_VariableList = G_PLCverbinding->LeesTest2(); 

如果G_PLCverbinding仅用于初始化静态成员,我会亲自使用static constructor代替:

ref class ManagedGlobals { 
    static ManagedGlobals() 
    { 
     PLCconnection^ plcVerbinding = gcnew PLCconnection(); 
     G_plcOnline = plcVerbinding->ConnectToPLC(); 
     G_VariableList = plcVerbinding->LeesTest2(); 
    } 
public: 
    static bool G_plcOnline; 
    static List<System::String^>^ G_VariableList; 
}; 

请记住,从静态构造函数中引发的任何异常,或作为第一个示例中的“内联”静态初始化的一部分,都会导致类型无法使用,因此最好确保您调用的PLCconnection类中的方法初始化静态变量时不会抛出。从MSDN

如果静态构造函数抛出一个异常,运行时就不会调用它第二次,并且类型将保持未初始化为你的程序正在运行的应用程序域的寿命。

最后,考虑到静态共享数据是线程安全问题的肥沃来源,所以如果要从不同线程读取和写入静态变量,则必须同步读/写操作使用锁定或其他同步机制。