【问题标题】:C# string format flag or modifier to lowercase paramC# 字符串格式标志或修饰符到小写参数
【发布时间】:2009-12-03 12:41:27
【问题描述】:

是否可以在字符串格式参数上指定某种标志或修饰符以使其小写或大写?

我想要的示例:

String.Format("Hi {0:touppercase}, you have {1} {2:tolowercase}.", "John", 6, "Apples");

想要的输出:

嗨,约翰,你有 6 个苹果。

PS:是的,我知道我可以在以字符串格式使用参数之前更改参数的大小写,但我不想要这个。

【问题讨论】:

  • 我知道你不想要它,但我不明白为什么只在字符串参数上调用 .tolower() 或 .toupper() 是个问题。
  • "我不明白为什么只在字符串参数上调用 .tolower() 或 .toupper() 是个问题" - 例如,数据绑定。
  • 我也遇到了同样的情况。 .ToLower() 对我不起作用的原因是格式化字符串来自数据库(即,它可以由最终用户配置)。

标签: c# string formatting


【解决方案1】:

只有填充和对齐格式......所以简单的方法就像你说的那样,使用"John".ToUpper()"John".ToLower()

另一种解决方案是创建自定义IFormatProvider,以提供您想要的字符串格式。

这就是IFormatProvider 和 string.Format 调用的外观。

public class CustomStringFormat : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;

    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        string result = arg.ToString();

        switch (format.ToUpper())
        {
            case "U": return result.ToUpper();
            case "L": return result.ToLower();
            //more custom formats
            default: return result;
        }
    }
}

调用将如下所示:

String.Format(new CustomStringFormat(), "Hi {0:U}", "John");

【讨论】:

  • 在 DisplayFormatAttribute 的范围内有没有办法做到这一点?
  • 如果不指定格式会出现NullReferenceException,所以需要在Format()方法中添加空检查条件。
【解决方案2】:

简而言之,不; AFAIK 你必须修复源值,或者使用你自己的替换 string.Format。请注意,如果您要传入自定义文化(到 string.Format),您可能希望使用 culture.TextInfo.ToLower(s),而不仅仅是 s.ToLower()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 2020-06-07
  • 2020-03-01
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多