简体   繁体   English

VB代码转换为C#编译错误

[英]vb code converted to c# compilation error

I had a code for getting the hdd id written in vb.net 我有一个代码来获取写在vb.net中的硬盘ID

Now I need to re-write the code into c#. 现在,我需要将代码重新编写为c#。 I have converted the vb.net code to c# but it is not compiling. 我已经将vb.net代码转换为c#,但尚未编译。

Below is the vb.net code 下面是vb.net代码

Dim hdCollection As ArrayList = New ArrayList()

Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive")

For Each wmi_HD As ManagementObject In searcher.Get()
    Dim hd As HardDrive = New HardDrive()
    hd.Model = wmi_HD("Model").ToString()
    hd.Type = wmi_HD("InterfaceType").ToString()

    hdCollection.Add(hd)
Next wmi_HD

here is the converted C# code: 这是转换后的C#代码:

ArrayList hdCollection = new ArrayList();

              ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

              foreach (ManagementObject wmi_HD in searcher.Get())
              {

                  HardDrive hd = new HardDrive();
                  hd.Model = wmi_HD("Model").ToString();
                  hd.Type = wmi_HD("InterfaceType").ToString();

                  hdCollection.Add(hd);
              }

Following is the error I am getting when compiling the c# code: 以下是我在编译C#代码时遇到的错误:

'wmi_HD' is a 'variable' but is used like a 'method' “ wmi_HD”​​是一个“变量”,但其用法类似于“方法”

Please help! 请帮忙!

The VB code performs a subscript (indexed) access. VB代码执行下标(索引)访问。 In C#, this converts to a call to the this[] property. 在C#中,这将转换为对this[]属性的调用。 So the call needs square braces in C#: 因此,调用需要在C#中使用方括号:

hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();

Apart from that, there's one thing wrong with both codes: Do not use ArrayList , the type is obsolete. 除此之外,两个代码都有一处错误:不要使用ArrayList ,该类型已过时。 In fact, the same is true for (most of) the other types in the System.Collections namespace. 实际上, System.Collections命名空间中的(大多数)其他类型也是如此。 The types have been replaced by generic classes in the System.Collections.Generic namespace. 这些类型已由System.Collections.Generic命名空间中的通用类替换。

In your case, you want a List<string> instead of the ArrayList (or, in VB, List(Of String) ). 在您的情况下,您需要一个List<string>而不是ArrayList (或者在VB中是List(Of String) )。

You have not converted the wmi_HD indexers properly. 您尚未正确转换wmi_HD索引器。

Change these lines: 更改这些行:

hd.Model = wmi_HD("Model").ToString();
hd.Type = wmi_HD("InterfaceType").ToString();

To: 至:

hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();

Try: 尝试:

hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();

Square brackets, not round. 方括号,不是圆形的。

Try 尝试

hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM