C# 检查对象是否可以强制转换为特定值类型?
我有一个哈希表,其中包含解析某个JSON的结果:C# 检查对象是否可以强制转换为特定值类型?,c#,C#,我有一个哈希表,其中包含解析某个JSON的结果:decodedJsondecodedJson[“key”]可以是int、double、float、decimal或字符串。如果它是一个数字(我计划使用(decimal)decodedJson[“key”]),则需要将其转换为十进制,否则需要处理错误 确定该值的最有效方法是什么?如果对象是十进制的,您可以这样做 if (decodedJson["key"] is decimal) { //do your action } if (decodedJs
decodedJson
decodedJson[“key”]
可以是int、double、float、decimal或字符串。如果它是一个数字(我计划使用(decimal)decodedJson[“key”]
),则需要将其转换为十进制,否则需要处理错误
确定该值的最有效方法是什么?如果对象是十进制的,您可以这样做
if (decodedJson["key"] is decimal)
{
//do your action
}
if (decodedJson["key"] is decimal)
{
//Your code here
}
Decimal.TryParse,下面的文档链接:
is操作员可能是您的最佳选择
根据这个问题,if decodedJson[“key”]可以是int、float、double、decimal或字符串中的任意值。我们需要检查所有类型
if(decodedJson["key"] is int || decodedJson["key"] is float || decodedJson["key"] is double || decodedJson["key"] is decimal)
{
decimal convereted_value = (decimal) decodedJson["key"];
// Rest of your code here
}
else
{
// Error handling code here.
}
由于它可以是任何数字类型,您可能需要:
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
如果要将其转换为不是实际基础类型的类型,则简单强制转换将不起作用<代码>转换类具有它所需的全面测试
或者,如果您愿意,可以将其完全通用化:
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);
}
是的,我们的想法是一样的:)考虑到类型是
int
,您不能强制转换为decimal
类型,这同样是有风险的Convert
class是最好的选择。可能Convert类是最好的选择,但是你可以将int转换为decimal,看看这个fiddle Niral,当然这是可能的。但是当值类型被装箱时,不能强制转换它。例如,尝试:objecti=0;十进制d=(十进制)i代码>
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);
}
var i = decodedJson["key"];
if (i.GetType().IsNumeric())
i.To<decimal>();
else
//handle