Globals 接口

更新:2007 年 11 月

Globals 对象是一个缓存,它在每个 Visual Studio 环境会话的持续时间内存储数据,并可以使用 VariablePersists 属性在各会话间存储数据。

命名空间:  EnvDTE
程序集:  EnvDTE(在 EnvDTE.dll 中)

语法

声明
<GuidAttribute("E68A3E0E-B435-4DDE-86B7-F5ADEFC19DF2")> _
Public Interface Globals
用法
Dim instance As Globals
[GuidAttribute("E68A3E0E-B435-4DDE-86B7-F5ADEFC19DF2")]
public interface Globals
[GuidAttribute(L"E68A3E0E-B435-4DDE-86B7-F5ADEFC19DF2")]
public interface class Globals
public interface Globals

备注

例如,Globals 对象允许程序具有在执行之间值保持不变的全局变量。它还可以用于允许命令实现默认值,例如如果某个命令每次运行时都要求用户输入信息,就可以使该命令实现默认值。此外,它还可以用于在被调用一定次数后更改自己的行为。

数据以名称/变量值对的形式存储在 Globals 对象中。对于这些名称/值对,可以选择用 VariablePersists 属性将其存储到磁盘上,以便在 Visual Studio 的不同会话间维护它们的状态(作为一个字符串)。

说明:

无法保存包含对象或 SafeArrays 的变量。如果值可以保存为字符串,则保存时将采用其本机格式。

外接程序或宏还可以使用 Globals 对象在 Visual Studio 会话之间保存每个用户专用的用户定义数据。它们还可以使用 Globals 对象将数据保存为解决方案 (.sln) 文件,也可以使用该对象在解决方案 (.sln) 文件中检索数据。

使用 VariableValue 属性保存或读取使用 Globals 对象存储的值。

说明:

VariableValue 名称字符串不能包括空格、冒号 (:) 或句点 (.) 字符。如果名称包含任何这些字符,则会收到错误“值不在预期的范围内”。

示例

Sub OnAddinLoaded(ByVal dte As DTE)
    ' Count the number of times an add-in is loaded
    ' and store the value in the solution.
    Dim globals As Globalsglobals = dte.Solution.Globals
    If globals.VariableExists("AddinLoadCounter") Then
        ' The counter has already been set, so increment it.
        Dim int32 As System.Int32
        int32 = System.Int32.Parse(CStr(globals("AddinLoadCounter")))
        int32 += 1
        globals("AddinLoadCounter") = int32.ToString()
    Else
        ' Counter has never been set, so create and initialize it.
        globals("AddinLoadCounter") = 1.ToString()
        globals.VariablePersists("AddinLoadCounter") = True
    End If
    MsgBox("This add-in has been loaded: " & _
    globals.VariableValue("AddinLoadCounter") & " times.")
End Sub
void OnAddinLoaded(_DTE applicationObject)
{
    // Count the number of times an add-in is loaded
    // and store the value in the solution.
    Globals globals;
    globals = applicationObject.Solution.Globals;
    if(globals.get_VariableExists("AddinLoadCounter"))
    {
        // The counter has already been set, so increment it.
        System.Int32 int32;
        int32 = System.Int32.Parse((string)
        globals["AddinLoadCounter"]);
        int32++;
        globals["AddinLoadCounter"] = int32.ToString();
    }
    else
    {
        // Counter has never been set, so create and initialize it.
        globals["AddinLoadCounter"] = 1.ToString();
        globals.set_VariablePersists("AddinLoadCounter", true);
    }
    System.Windows.Forms.MessageBox.Show("This add-in has been loaded: 
    " + globals.VariableValue["AddinLoadCounter"] + " times.");
}

另请参见

参考

Globals 成员

EnvDTE 命名空间

其他资源

在项目和解决方案中保持信息