将集合中的managementtobject对象读入类型化变量

本文关键字:类型化 变量 对象 managementtobject 集合 | 更新日期: 2023-09-27 17:49:27

我有一个ManagementObject的集合。管理对象的属性是不同的类型:int, string, array, DateTime等。

我想把属性值读入合适的变量类型

ManagementScope manScope = new ManagementScope(@"''.'root'virtualization'v2"); 
manScope.Connect();
ObjectQuery queryObj = new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection = vmSearcher.Get();
foreach (ManagementObject vm in vmCollection) {
    **//Fine so far.  This is not a question about iteration.**
    //Now I want to so something programmatic with the values.
    //If it is a string, this is fine:
    string myString = vm["Description"].ToString();
    //If it is an integer, I can go like this:
    int myInt =int.Parse(vm["EnabledState"].ToString());
    //But surely c# has a better way than that? Turn it into a string and then an int?
    //If it is DateTime, I have no idea what to do - DateTime.Parse() doesn't work:
   //DateTime myDate = DateTime.Parse(vm["LastSuccessfulBackupTime"].ToString());
}

我已经阅读了文档(没有一个这样的例子)。我使用的是WMI Code Creator,它也没有帮助,因为它只是把所有东西都放到控制台:控制台。WriteLine("InstallDate: {0}", queryObj["InstallDate"]);

将集合中的managementtobject对象读入类型化变量

这是非常不寻常的要求,但仍然-我建议通过类详细信息Msvm_computersystem并创建具有相同数据类型的变量。获得集合中的数据后,可以尝试将其解析为相应的变量。