[英]How to access an object array as Hashvalue in C#
Why does the following throws the compile error [] cannot be applied to object.
为什么以下引发编译错误的错误
[] cannot be applied to object.
(rough translation from german)? (德语翻译)?
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
}
I expected entry.Value
to be an array of objects but apparently the compiler thinks it's just an object. 我期望
entry.Value
是一个对象数组,但是显然编译器认为它只是一个对象。 What is wrong here? 怎么了
The error is coming because DictionaryEntry
does not have an array as a property for Value. 错误即将到来是因为
DictionaryEntry
没有数组作为Value的属性。 Below is the structure of DictionaryEntry
. 下面是
DictionaryEntry
的结构。 You must use entry.Value
instead of entry.Value[0]
您必须使用
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; }
}
EDIT 编辑
To make it work you have to cast it. 为了使它起作用,您必须将其转换。 Use following code
使用以下代码
Registry.SetValue(keyPath,
(string)entry.Key,
((object[])(entry.Value))[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.