2015-10-07 23 views
1

为什么下面的代码会引发编译错误[] cannot be applied to object.(德文粗略翻译)?如何访问对象数组作为C#中的Hashvalue

Hashtable entrys = new Hashtable(); 
string keyPath = "HKEY_CURRENT_USER\\Software\\Test"; 
string entryName = "testName"; 

entrys.Add(entryName, new object[]{256, RegistryValueKind.DWord}); // seems to work 

foreach(DictionaryEntry entry in entrys) 
{ 
    Registry.SetValue(keyPath, 
         (string)entry.Key, 
         entry.Value[0], // error here 
         entry.Value[1]); // and here 
} 

我预计entry.Value是对象的数组,但显然编译器认为它只是一个对象。这里有什么问题?

+0

检查此为Registry.SetValue的正确用法-https://msdn.microsoft.com/en-us/library/3dwk5axy(V = vs.110).ASPX –

+2

使用'字典<字符串,对象[]>'而不是'Hashtable'。哈希表不是强类型的 –

+0

您需要施放它。 – kevintjuh93

回答

2

错误即将发生,因为DictionaryEntry没有将数组作为Value的属性。以下是DictionaryEntry的结构。您必须使用entry.Value代替entry.Value[0]

// Summary: 
    // Defines a dictionary key/value pair that can be set or retrieved. 
    [Serializable] 
    [ComVisible(true)] 
    public struct DictionaryEntry 
    {    
     public DictionaryEntry(object key, object value); 

     // Summary: 
     //  Gets or sets the key in the key/value pair. 
     // 
     // Returns: 
     //  The key in the key/value pair. 
     public object Key { get; set; } 
     // 
     // Summary: 
     //  Gets or sets the value in the key/value pair. 
     // 
     // Returns: 
     //  The value in the key/value pair. 
     public object Value { get; set; } 
    } 

编辑

为了使它工作,你要投它。使用以下代码

Registry.SetValue(keyPath, 
        (string)entry.Key, 
        ((object[])(entry.Value))[0]); 
+0

因此,这意味着'entrys.Add(entryName,new object [] {256,RegistryValueKind.DWord});'实际上是无效的,因为DictionaryEntry不能将数组保存为值? 我认为'entry.Value'返回我可以通过'[]'操作符访问的对象数组? 我应该使用'ArrayList'来替代还是我可以做什么? – LPrc

+1

我编辑了我的答案。见编辑部分。它的工作。 –

+1

entry.Value是一个对象数组,字典只是没有意识到这一点。这就是铸造工作的原因。您可能想使用'System.Collection.Generic.HashSet ',因为它有一个通用的实现(允许您为项目选择一种类型)。 – MrFox