C#字符串格式标志或修饰符为小写参数

rjl*_*pes 41 c# string formatting

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

我想要的例子:

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

通缉输出:

嗨约翰,你有6个苹果.

PS:是的我知道我可以在以字符串格式使用之前更改参数的情况,但我不想这样做.

Gui*_*non 65

只有填充和排列形成...所以简单的方法就像你说的,使用"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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

电话会看起来像:

String.Format(new CustomStringFormat(), "Hi {0:U}", "John");
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 7

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