gpt4 book ai didi

c# - 无效查询 C#

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:32 24 4
gpt4 key购买 nike

今天我用 C# 编写了我的第二个代码为什么它不起作用?代码(看起来)是正确的!

错误代码:无效查询

代码:

  static void Main(string[] args)
{
GetComponent("Win32_Processor", "Name");
Console.Read();
Console.ReadKey();
}

private static void GetComponent(string hwclass, string syntax)
{
ManagementObjectSearcher mos = new ManagementObjectSearcher ("root\\CIMV2","SELECT * FROM" + hwclass);
foreach(ManagementObject mj in mos.Get())
{
Console.WriteLine(Convert.ToString(mj[syntax]));
}


}

最佳答案

请使用格式化字符串插值 (C# 6.0+) 以避免语法错误:

private static void GetComponent(string hwclass, string syntax) {
//DONE: keep query readable
string query =
$@"select *
from {hwclass}"; // <- you've missed space here

//DONE: wrap IDisposable into using
using (ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", query)) {
foreach(ManagementObject mj in mos.Get())
Console.WriteLine(Convert.ToString(mj[syntax]));
}
}

关于c# - 无效查询 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com