我尝试了:
ManagementObjectCollection searchResults = new ManagementObjectSearcher(
"select * from " + key).Get(); // for testing use => "Win32_ComputerSystem"
int counter = 0;
foreach (ManagementBaseObject? searchResult in searchResults) {
if (searchResult is null)
continue;
counter += 1;
foreach (PropertyData? property in searchResult.Properties) {
if (property.Name is null) {
continue;
}
object tmpobj = searchResult.GetPropertyValue(property.Name);
string propertyname = counter + " | " + property.Name;
if (tmpobj is null) {
continue;
}
else if (tmpobj is IEnumerable<object> tmpcollection) {
foreach (object item in tmpcollection) {
if (tmpobj is null) {
continue;
}
else {
descriptor.Properties.Add(propertyname, item.ToString());
}
}
}
else {
descriptor.Properties.Add(propertyname, tmpobj.ToString());
}
}
}
继承,并且包括struct在内的任何数据类型都应继承“对象”
,我认为它应该可以工作,但是由于某种原因,它不适合结构(至少用于双重,短,ushort等)。 (仅供参考:我正在使用最新的.net8) 我从微软到结构的信息[16.4.3继承]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/structsists 可以使用更轻松的测试以下代码:
short[] shorts =
{
11,
22,
33,
623,
2321,
0
};
short shorter = 0;
object objshorts = shorts as object;
if (shorts is IEnumerable<short>) ; // => true
if (shorts is IEnumerable<ValueType>) ;// => false
if (shorts is IEnumerable<object>) ; // => false
if (shorter is object) ; // => true
我的问题是:
为什么它不起作用?我需要改变什么?
Console.WriteLine (shorts is IEnumerable<short>) ; // => true
Console.WriteLine(shorts is Array) ;// => true
Console.WriteLine(shorts.All(_=>_.GetType().IsValueType)); // => true
Console.WriteLine(shorter is object) ; // => true