我在.net 6和VS 2022中有以下代码。为了保持轻松,我评论了这条线后面的警告。我不知道怎么解决这个问题。希望有人能帮我。
try
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
using (ManagementObjectCollection managementObjectCollection = searcher.Get())
{
ManagementObject? managementObject = managementObjectCollection.OfType<ManagementObject>().FirstOrDefault();
hardwareComputerName = managementObject["name"].ToString().ToLower(); // 'managementObject' may be null here. CS8602 Dereference of a possibly null reference. (2x)
hardwareComputerManufacturer = managementObject["Manufacturer"].ToString(); // 'managementObject' is not null here. CS8601 Possible null reference assignment.
hardwareComputerModel = managementObject["model"].ToString(); // 'managementObject' is not null here. CS8601 Possible null reference assignment.
}
}
catch (Exception)
{
MessageBox.Show("Problem im Abschnitt Name, Hersteller und Modell.");
}
managementObject
可能是null
(它可以为null,FirstOrDefault
可能返回null
(,并且在其声明后的行上,您访问managementObject
的一个成员而不首先验证它是否为null,这可能会导致null引用异常,因此会发出警告。
你有几个选择,其中两个是
-
用
First
替换FirstOrDefault
;如果找不到元素,但结果从不为null
,则将抛出 -
测试null,如果不是null,则仅执行成员访问语句
管理对象?managementObject=。。。FirstOrDefault((;
if(null!=managementObject({。。。}
这是没有给出警告的代码。感谢Moho的帮助。
try
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
using (ManagementObjectCollection managementObjectCollection = searcher.Get())
{
ManagementObject? managementObject = managementObjectCollection.OfType<ManagementObject>().First();
hardwareComputerName = managementObject["name"].ToString()?.ToLower() ?? "Default";
hardwareComputerManufacturer = managementObject["Manufacturer"].ToString() ?? "Default";
hardwareComputerModel = managementObject["model"].ToString() ?? "Default";
}
}
catch (Exception)
{
MessageBox.Show("Problem im Abschnitt Name, Hersteller und Modell.");
}