开发者

vb code converted to c# compilation error

I had a code for getting the hdd id written in vb.net

Now I need to re-write the code into c#. I have converted the vb.net code to c# but it is not compiling.

Below is the vb.net code

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:

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:

'wmi_HD开发者_JS百科' is a 'variable' but is used like a 'method'

Please help!


The VB code performs a subscript (indexed) access. In C#, this converts to a call to the this[] property. So the call needs square braces in 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. In fact, the same is true for (most of) the other types in the System.Collections namespace. The types have been replaced by generic classes in the System.Collections.Generic namespace.

In your case, you want a List<string> instead of the ArrayList (or, in VB, List(Of String)).


You have not converted the wmi_HD indexers properly.

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜