You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何生成以点为小数分隔符的Query String

解决方案

要让decimal类型的属性值使用点作为小数分隔符,核心是在格式化数值时指定CultureInfo.InvariantCulture(该文化始终使用点作为小数分隔符,不受系统区域设置影响)。你需要修改LINQ查询中获取属性值的部分,对数值类型做特殊格式化处理:

完整修改后的代码

using System.Globalization;

Person person = new()
{
    Name = "Tom",
    Account = 1000.123m,
};

var properties = from p in person.GetType().GetProperties()
                 where p.GetValue(person, null) != null
                 select p.Name.ToLower() + "=" + FormatPropertyValue(p.GetValue(person));

Console.WriteLine(String.Join("&", properties.ToArray()));


class Person
{
    public string Name { get; set; } = String.Empty;
    public decimal Account { get; set; }
}

private static string FormatPropertyValue(object value)
{
    // 对实现IFormattable的类型(如decimal、int、double等数值类型)用不变文化格式化
    if (value is IFormattable formattableValue)
    {
        return formattableValue.ToString(null, CultureInfo.InvariantCulture);
    }
    // 非数值类型直接转字符串
    return value.ToString() ?? string.Empty;
}

关键说明

  1. 引入System.Globalization命名空间,才能使用CultureInfo.InvariantCulture。
  2. 新增FormatPropertyValue辅助方法,统一处理属性值格式化:
    • 数值类型都实现了IFormattable接口,通过该接口指定不变文化,确保小数分隔符为点。
    • 其他类型(如string)直接调用默认ToString()即可。
  3. 如果不想单独写辅助方法,也可以直接在LINQ查询内处理:
    select p.Name.ToLower() + "=" + 
           (p.GetValue(person) is IFormattable fmt 
               ? fmt.ToString(null, CultureInfo.InvariantCulture) 
               : p.GetValue(person).ToString());
    

输出结果

修改后运行代码,会输出你期望的格式:

name=Tom&account=1000.123

内容的提问来源于stack exchange,提问作者Frankie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:53:25