2015-04-29 37 views
1

我正在创建一个VSTO插件。我希望在Outlook开始时创建一个字典,然后我可以从OutlookRibbon类中的方法访问它。创建这样一本字典的最佳实践或适当的方法是什么?我现在有一种方法,即在使用它的方法中创建字典,因为它每次都会调用它,效率非常低。下面是代码:VSTO Addin中的C#访问数据

public partial class OutlookRibbon 
{ 
    private void OutlookRibbon_Load(object sender, RibbonUIEventArgs e) 
    { 
     genMyDict(); 
    } 

    private void button1_Click(object sender, RibbonControlEventArgs e) 
    { 
     Archive(); 
    } 
    void genMyDict() 
    { 
     Dictionary<string, string> myDict= new Dictionary<string, string>(); 
     myDict.Add("@x.com", "x"); 
     // many lines of this 

    } 

    void Archive() 
    { 
     if (myDict.ContainsKey("@x.com")) { // run code } 
    } 

显然,这会引发错误myDict在目前情况下不存在存档()

我应该如何构建这种以便词典只能创建一个时间,但仍然可以从OutlookRibbon类中的其他方法访问?我似乎无法使其工作。有没有更好的方法来创建在VSTO outlook插件中使用像这样的字典?

+0

无耻插件 - >查看我的文章[C#Dictionary Tricks](http://omegacoder.com/?p=188)了解一些很酷的操作字典的方法。 – OmegaMan

回答

1

myDict不会在目前情况下通过使其成为OutlookRibbon类的属性存在

更改词典的范围。这将扩大其范围远离方法genMyDict本地化堆栈

public Dictionary<string, string> MyDictionary { get; set; } 

void genMyDict() 
{ 
    MyDictionary = new Dictionary<string, string>(); 
    MyDictionary.Add("@x.com", "x"); 
    ... 
} 

void Archive() 
{ 
    if (MyDictionary.ContainsKey("@x.com")) { // run code } 
} 

这将允许一切访问它。对于范围的改变,只允许一种方法访问整个班级。

+0

我无法找到构造函数,因为我认为这是生成的,我不想意外覆盖它。 – shenk

+0

@shenk对不起,我错误的私有方法'genMyDict'作为构造函数。因此,不要像我说的那样在构造函数中分配字典,而应该忘记将分配保存在'genMyDict'中,而是将其分配给您在类“OutlookRibbon”中为其创建的属性。 – OmegaMan

+0

你能给我一个小例子吗? – shenk

相关问题