'Convert multiline if-else function to a generic one
I start learning about generics, and I wonder if I can reduce the repetition from this function using generic: My first thought was to make replace all the parse function with "T" = T.Parse( but it seem that it doesn't work at all...
private string GetHexa(PropertyInfo prop, object propValue, FrameTemplate payload)
{
Type t = prop != null ? prop.PropertyType : typeof(object);
Debug.WriteLine(t.Name);
switch (t.Name)
{
case "String":
byte[] str = HartByteArrayExtensions.LatinToByteArray(payload.Deca);
return ByteArrayExtensions.ToHexString(str);
case "UInt8":
string uint8 = int.Parse(payload.Deca).ToString("X");
return ByteArrayExtensions.ToHexString(new byte[1] { Convert.ToByte(uint8) });
case "HartUnitCode":
var hartUnitCode = (byte)propValue;
return ByteArrayExtensions.ToHexString(new byte[1] { Convert.ToByte(hartUnitCode) });
case "Byte[]":
return ByteArrayExtensions.ToHexString((byte[])propValue); ;
case "UInt16":
byte[] uint16 = ByteArrayExtensions.ToByteArray(UInt16.Parse(payload.Deca));
return ByteArrayExtensions.ToHexString(uint16);
case "UInt24":
byte[] uint24 = ByteArrayExtensions.ToByteArray(UInt24.Parse(payload.Deca));
return ByteArrayExtensions.ToHexString(uint24);
case "UInt32":
byte[] uint32 = ByteArrayExtensions.ToByteArray(UInt32.Parse(payload.Deca));
return ByteArrayExtensions.ToHexString(uint32);
case "HartDate":
byte[] hartHartDate = HartDate.ToByteArray(new HartDate(payload.Deca));
return ByteArrayExtensions.ToHexString(hartHartDate);
case "Byte":
byte[] buf = new byte[1] { byte.Parse(payload.Deca) };
return ByteArrayExtensions.ToHexString(buf);
case "PackedAscii":
byte[] packedascii = PackedAscii.ToByteArray((PackedAscii)payload.Deca);
return ByteArrayExtensions.ToHexString(packedascii);
case "HartTime":
byte[] hartTime = HartTime.ToByteArray(new HartTime(payload.Deca));
return ByteArrayExtensions.ToHexString(hartTime);
case "Single":
float flt;
if (propValue.GetType().Name == "String")
{
flt = float.Parse((string)propValue);
}
else
{
flt = (float)propValue;
}
return ByteArrayExtensions.ToHexString(ByteArrayExtensions.ToByteArray(flt));
default:
return string.Empty;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
