Поскольку это может быть любой числовой тип, вы можете:
var i = decodedJson["key"];
bool isNumeric = i is byte || i is sbyte || i is short || i is ushort ||
i is int || i is uint || i is long || i is ulong ||
i is float || i is double || i is decimal;
if (isNumeric)
Convert.ToDecimal(i);
else
//handle
Если вы хотите, чтобы преобразовать его к типу, который не является фактическим базовый тип, простой бросок не будет Работа. Convert
класс имеет всесторонние тесты, которые ему понадобятся.
Или сделать его родовое весь путь, если вы хотите:
public static T To<T>(this object source) where T : IConvertible
{
return (T)Convert.ChangeType(source, typeof(T));
}
public static bool IsNumeric(this Type t)
{
return t.In(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort),
typeof(int), typeof(uint), typeof(long), typeof(ulong),
typeof(float), typeof(double), typeof(decimal));
}
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Или найти более точную версию IsNumeric
here.
Итак, теперь вы звоните:
var i = decodedJson["key"];
if (i.GetType().IsNumeric())
i.To<decimal>();
else
//handle
Да, мы думаем одинаково :) –