Is there any way to merge these two classes into one class to reduce duplicated code?

  • Thread starter Thread starter E-John
  • Start date Start date
E

E-John

Guest
Dear All,


There are two classes. The only difference between these two classes is the array size of NaemByteUnicode , one is 20 bytes and the other is 40 bytes.

Because I need to get the size of the class, the following description is needed

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)]

Is there any way to merge these two classes into one class to reduce duplicated code?


Thanks and Best regards,

E-John

namespace DynamicCharSize
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class ElementNameByte40
{
public ushort Index;
public UInt32 IP;

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)]
public byte[] NameByteUnicode = new byte[40];

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Attribute = new byte[6];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Password = new byte[8];
}


[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class ElementNameByte20
{
public ushort Index;
public UInt32 IP;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] NameByteUnicode = new byte[20];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Attribute = new byte[6];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Password = new byte[8];
}

class Program
{
static void Main(string[] args)
{
ElementNameByte40 elementNameByte40 = new ElementNameByte40();

int sizeElementNameByte40 = Marshal.SizeOf(typeof(ElementNameByte40));
Console.WriteLine("sizeElementNameByte40 = {0}", sizeElementNameByte40);


ElementNameByte20 elementNameByte20 = new ElementNameByte20();
int sizeElementNameByte20 = Marshal.SizeOf(typeof(ElementNameByte20));
Console.WriteLine("sizeElementNameByte20 = {0}", sizeElementNameByte20);

Console.ReadLine();
}
}
}

Continue reading...
 

Similar threads

O
Replies
0
Views
80
okardak onur
O
J
Replies
0
Views
77
jerome_coder
J
Back
Top