c# - Convert.ChangeType不接受十进制的 "1E-5"科学计数法,如何修复?

标签 c# .net-5

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/

相关文章:

c# - System.Text.Json 未序列化 List<T>

C# 如何使我的 sqlDataReader 脱机?

c# - 'where()' 方法的问题

c# - 查询 XML 以提取一条记录并将数据绑定(bind)到各个文本 block

.net - Azure 函数 .net 5 UseSqlServer 配置

c# - 信封 Odata 响应

c# - 在 ASP.NET Core MVC 1.0.1 (ASP.NET Core 1.1) 中覆盖 Controller / Action 中的全局 Action 过滤器

c# - 访问 S3FileInfo 属性时发生 AmazonS3Exception

c# - Visual Studio 2019 v16.6无法构建.net5控制台应用程序并引发错误: . NETFramework,Version = v5.0未找到

c# - 如果默认添加 DbContext 范围,为什么还要添加它?