【发布时间】:2020-11-26 13:01:58
【问题描述】:
我使用管理来访问设备属性,并在下面编写了一个代码来创建一个字典数组。我的应用程序在listview 控件中显示属性;所以我需要将所有属性值转换为简单的字符串
Dictionary<string,string>[] getInfo(string k) {
// using `k` as management-key
var mos = new ManagementObjectSearcher($"select * from {k}");
var devices = new List<Dictionary<string, string>>();
var mosc = mos.Get(); // mosc is a collection of all devices with same key
foreach (var device in mosc) {
var properties = new Dictionary<string, string>();
foreach (var p in device.Properties) {
if (p.Value != null) {
if (p.IsArray) {
// I have problem in here
// my application must convert p.value to string
var collection = (IEnumerable<object>)p.Value
properties[p.Name] = string.Join(", ", collection.Select(x=>x.ToString()));
} else
properties[p.Name] = p.Value.ToString();
} else properties[p.Name] = "";
}
devices.Add(properties);
}
return devices.ToArray();
}
p.Value 类型是object,但有时它包含像UInt[] 或String[] 这样的数组,我从stackoverflow 找到了部分代码,但它没有帮助我,它说:
System.InvalidCastException:'无法将'System.UInt16[]'类型的对象转换为'System.Collections.Generic.IEnumerable`1[System.Object]'。'
我也试过下面的代码,但它说的是同样的事情:
int[] array = new int[] { 0, 1, 2 }; // <- I haven't access to `array` in my main problem
object obj=array;
// I only can use `obj`
// `obj` is similar to `p.Value` here
IEnumerable<object> collection = (IEnumerable<object>)obj; // <- this line throws exception!
string output=string.join(", ",collection.Select(x=>x.ToString()));
我也试过这个代码:
var collection= p.Value as IEnumerable;
// ^ found this line from stackoverflow
// says: Using the generic type 'IEnumerable<T>' requires 1 type arguments
var collection= p.Value as IEnumerable<object>
// `collection` will be null
var collection= (object[]) p.Value
// says: Unable to cast object of type 'System.Int32[]' (or some something like String[]) to type 'System.Object[]'.
【问题讨论】:
标签: c# arrays ienumerable enumerable