System.String转System.Decimal泛型转换报错,求问题排查与解决
类型转换错误排查:System.InvalidCastException 问题解决
报错信息
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Decimal'.'
错误代码实现及调用
private static T1 StringToDecimal<T1, T2>(T2 dummydata) { var type = typeof(T1);//string var type2 = typeof(T2);//decimal Console.WriteLine("Type of T1 is : " + type); Console.WriteLine("Type of T2 is : " + type2); return (T1)Convert.ChangeType(dummydata, typeof(T2), CultureInfo.InvariantCulture); //调用代码 //string? _dummydata = "8468.45"; //var getresult_ = StringToDecimal<string, decimal>(_dummydata); }
错误原因分析
- 泛型参数顺序与实际需求完全颠倒:你需要把
string输入转换为decimal结果,但调用时指定的<string, decimal>对应方法定义里的T1=string(返回类型)、T2=decimal(参数类型),实际传入的却是string类型参数,和T2的decimal类型冲突,直接导致类型不匹配。 - 转换目标类型错误:
Convert.ChangeType的目标类型写为typeof(T2),但实际应该转换为你需要的返回类型,这里的类型参数逻辑完全混乱。
修正后的可行代码
private static TToConvertTo StringToDecimal<TToConvertFrom, TToConvertTo>(TToConvertFrom dummydata) { return (TToConvertTo)Convert.ChangeType(dummydata, typeof(TToConvertTo), CultureInfo.InvariantCulture); }
正确调用示例
string? _dummydata = "8468.45"; decimal getresult_ = StringToDecimal<string, decimal>(_dummydata);
内容的提问来源于stack exchange,提问作者Rabiranjan Singh
相关产品推荐
相关产品推荐

