I write the code to iterate the class properties.
static class PacketCoder
{
public static byte[] PacketToData<T>(AppSignal signal, T packet)
{
byte[] dataBuf = new byte[1000];
byte[] dataTemp = BitConverter.GetBytes((short)signal);
Array.Copy(dataTemp, dataBuf, dataTemp.Length);
int dataIndex = dataTemp.Length;
Type t = packet.GetType();
var props = t.GetProperties();
foreach (var prop in props)
{
string name = prop.Name;
object value = prop.GetValue(packet);
if (value.GetType() == typeof(bool))
{
dataTemp = BitConverter.GetBytes((bool)value);
}
else if (value.GetType() == typeof(short))
{
dataTemp = BitConverter.GetBytes((short)value);
}
else if (value.GetType() == typeof(int))
{
dataTemp = BitConverter.GetBytes((int)value);
}
Array.Copy(dataTemp, 0, dataBuf, dataIndex, dataTemp.Length);
dataIndex += dataTemp.Length;
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Length: {0}", dataTemp.Length);
Console.WriteLine("Value: {0}", value);
Console.WriteLine("");
}
byte[] dataFinal = new byte[dataIndex];
Array.Copy(dataBuf, dataFinal, dataIndex);
return dataFinal;
}
}
I want to make the three if
to one:
if (value.GetType() == typeof(bool))
{
dataTemp = BitConverter.GetBytes((bool)value);
}
else if (value.GetType() == typeof(short))
{
dataTemp = BitConverter.GetBytes((short)value);
}
else if (value.GetType() == typeof(int))
{
dataTemp = BitConverter.GetBytes((int)value);
}
Some one can you tell me how to do this?