如何在Excel VSTO中更新CustomProperties集合中的值?

我正在使用VSTO在Excel插件上工作。 我刚刚遇到一个奇怪的问题,如果我尝试从CustomProperties中获取一个值,它会抛出一个COMexception,我不知道为什么。 有没有人遇到过这个? 这是我正在尝试使用的代码:

CustomProperties properties = worksheet.CustomProperties; properties.Add("name", "value"); Console.Write(properties["name"]); //this crashes COMException. Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) Console.Write(properties[0]); //and this crashes COMException.Exception from HRESULT: 0x800A03EC Console.Write(properties.Item[0]); //and this also crashes Exception from HRESULT: 0x800A03EC Console.Write(properties.Item["name"]); //and this crashes as well Type mismatch. Console.Write(properties.get_Item(0)); //this crashes again HRESULT: 0x800A03EC Console.Write(properties.get_Item("name"); //and this still crashes Type mismatch. 

我不知道如何使用这个集合。 我发现一个解决方法来读取属性:

 Dictionary<string, string> workingProperties = new Dictionary<string, string>(); foreach (dynamic custProp in properties) workingProperties.Add(custProp.Name, custProp.Value); string value = workingProperties["name"];// this works 

但是,当涉及到更新现有的属性 – 我卡住了,我需要一个方法来解决该集合中的项目,并没有删除或删除function首先删除它,然后添加一个新的具有相同的名称。

好的,写这篇文章,并实现了一个解决方法:

  string GetProperty(Worksheet ws, string name) { foreach (CustomProperty cp in ws.CustomProperties) if (cp.Name == name) return cp.Value; return null; } void SetProperty(Worksheet ws, string name, string value) { bool found = false; CustomProperties cps = ws.CustomProperties; foreach (CustomProperty cp in cps) { if (cp.Name == name) { found = true; cp.Value = value; } } if (!found) cps.Add(name, value); } 

仍然很奇怪,没有办法以正常的方式访问集合。