MRE:https://dotnetfiddle.net/M7WeMH
我有这个通用实用程序:
static T readValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
从文件中读取一些数据,这些数据都应该是十进制值,当文本采用科学记数法时,我会遇到异常,例如“1E-5”
- 这种情况在文件中很少出现。进一步测试我发现 decimal.Parse
也有同样的问题:
using System;
public class Program
{
static T readValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
public static void Main()
{
try
{
Console.WriteLine($"{readValue<decimal>("1E-5")}");
}
catch(Exception e)
{
Console.WriteLine(e);
}
try
{
Console.WriteLine($"{decimal.Parse("1E-5")}");
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Number.ParseDecimal(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info) at System.Convert.ToDecimal(String value, IFormatProvider provider) at System.String.System.IConvertible.ToDecimal(IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType) at Program.readValue[T](String value)
at Program.Main()System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Number.ParseDecimal(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info) at System.Decimal.Parse(String s) at Program.Main()
这个问题解释了如何修复它 decimal.Parse
( Parse a Number from Exponential Notation ),但我这个通用方法用于从 CSV 文件加载各种文件数据在很多地方......是否有等效的修复方法来避免大量代码重构?
最佳答案
这很丑陋,因为所有人都知道,但这里有一个如何完成特定类型行为的示例:
static T readValue<T>(string value) where T : struct
{
var type = typeof(T);
if (type == typeof(decimal))
{
// Put this return statement in a block that verifies the content of the string is scientific notation.
return (T)Convert.ChangeType(decimal.Parse(value, NumberStyles.Float), typeof(T));
}
return (T)Convert.ChangeType(value, typeof(T));
}
关于c# - Convert.ChangeType不接受十进制的 "1E-5"科学计数法,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69124740/