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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1839649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:18:50  来源:igfitidea点击:

C# string format flag or modifier to lowercase param

c#stringformatting

提问by rjlopes

Is it possible to specify some kind of flag or modifier on a string format param to make it lower case or upper case?

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

Example of what I want:

我想要的例子:

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

Wanted output:

想要的输出:

Hi JOHN, you have 6 apples.

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

PS: Yes I know that I can change the case of the param before using it in the string format, but I don't want this.

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

采纳答案by Guido Zanon

There's only padding and allignment formating... So the easy way is like you said, use "John".ToUpper()or "John".ToLower().

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

Another solution could be create a custom IFormatProvider, to provide the string format you want.

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

This is how will look the IFormatProviderand the string.Format call.

这就是IFormatProviderstring.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;
        }
    }
}

And the call will look like:

调用将如下所示:

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

回答by Marc Gravell

In short, no; AFAIK you'd have to fix the source values, or use your own replacement to string.Format. Note that if you are passing in a custom culture (to string.Format) you may want to use culture.TextInfo.ToLower(s), rather than just s.ToLower().

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