我需要將字節數組轉換爲不同的數據類型,例如uint16
或uint32
。下面的類包含一個填充了動作的字典,作爲Dictionary
實例中的值。行動是BitConverter.ToUInt16
或BitConverter.ToUInt32
。基於字符串調用方法
class DataTypes
{
private Dictionary<string, Action> _dict;
public DataTypes()
{
// create new dictionary
_dict = new Dictionary<string, Action>();
// fill dictionary with key-value pairs
_dict.Add("uint16", BitConverter.ToUInt16);
_dict.Add("uint32", BitConverter.ToUInt32);
_dict.Add("sint16", BitConverter.ToInt16);
_dict.Add("sint32", BitConverter.ToInt32);
}
// converts byte-array to specified type
public object getValue(string type, byte[] data, int pos) // e.g. type = "uint16"
{
if (_dict.ContainsKey(type))
return _dict[type](data, pos);
return null;
}
}
上面的代碼不運行,因爲編譯器需要一個帶'void ToUInt32()'簽名(帶大括號)的方法。
有誰知道我該怎麼做到這一點。
謝謝!我喜歡這個! – Boozzz 2014-10-08 09:50:34
@Boozzz如果解決方案沒有問題,那麼你應該將它標記爲答案 – 2014-10-08 10:57:11