C# equivalent to VB6 'Type'

2019-07-24 18:14发布

问题:

I am trying to port a rather large source from VB6 to C#. This is no easy task - especially for me being fairly new to C#.net. This source uses numerous Windows APIs as well as numerous Types. I know that there is no equivalent to the VB6 Type in C# but I'm sure there is a way to reach the same outcome. I will post some code below to further explain my request.

VB6:

Private Type ICONDIRENTRY
bWidth          As Byte
bHeight         As Byte
bColorCount     As Byte
bReserved       As Byte
wPlanes         As Integer
wBitCount       As Integer
dwBytesInRes    As Long
dwImageOffset   As Long
End Type

Dim tICONDIRENTRY()     As ICONDIRENTRY

ReDim tICONDIRENTRY(tICONDIR.idCount - 1)

For i = 0 To tICONDIR.idCount - 1
    Call ReadFile(lFile, tICONDIRENTRY(i), Len(tICONDIRENTRY(i)), lRet, ByVal 0&)
Next i

I have tried using structs and classes - but no luck so far.

I would like to see a conversion of this Type structure, but if someone had any clue as to how to convert the entire thing it would be unbelievably helpful. I have spent countless hours on this small project already.

If it makes any difference, this is strictly for educational purposes only.

Thank you for any help in advance, Evan

回答1:

struct is the equivalent. You'd express it like this:

struct IconDirEntry {
    public byte Width;
    public byte Height;
    public byte ColorCount;
    public byte Reserved;
    public int Planes;
    public int BitCount;
    public long BytesInRes;
    public long ImageOffset;
}

You declare a variable like this:

IconDirEntry entry;

Generally, in C#, type prefixes are not used, nor are all caps, except possibly for constants. structs are value types in C#, so that means that they are always passed by value. It looks like you're passing them in to a method that's populating them. If you want that usage, you'll have to use classes.



回答2:

I'm not exactly sure what your issue is but this is a small ex of how to use a struct.

struct aStrt
{
    public int A;
    public int B;
}

static void Main(string[] args)
{
    aStrt saStrt;
    saStrt.A = 5;
}


回答3:

Your question is not clear ..

What issues are you facing when you are using either struct or class and define those field members? Are you not able to access those members using an instance created for that class ??

Else, declare the class as static and make all the members inside the class also as static , so that u can access them without any instance being created!!



回答4:

Maybe you trying to get something like this?

struct IconDirEntry 
{
  public byte Width;
  // etc...
}

IconDirEntry[] tICONDIRENTRY = new IconDireEntry[tICONDIR.idCount - 1];