Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字符串格式标志或小写参数的修饰符_C#_String_Formatting - Fatal编程技术网

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

C#字符串格式标志或小写参数的修饰符,c#,string,formatting,C#,String,Formatting,是否可以在字符串格式参数上指定某种标志或修饰符,使其大写或小写 我想要的示例: String.Format("Hi {0:touppercase}, you have {1} {2:tolowercase}.", "John", 6, "Apples"); 想要的输出: 嗨,约翰,你有6个苹果 PS:是的,我知道在以字符串格式使用参数之前,我可以更改它的大小写,但我不想这样做。简而言之,不;好吧,您必须修复源代码值,或者使用自己的替换来string.Format。请注意,如果要传入自定义区域性

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

我想要的示例:

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

嗨,约翰,你有6个苹果


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

简而言之,不;好吧,您必须修复源代码值,或者使用自己的替换来
string.Format
。请注意,如果要传入自定义区域性(到
string.Format
),可能需要使用
culture.TextInfo.ToLower
,而不仅仅是
s.ToLower()。。。所以简单的方法就像你说的,使用
“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");

我知道你不想要它,但我不明白为什么对字符串参数调用.tolower()或.toupper()会有问题。“我不明白为什么对字符串参数调用.tolower()或.toupper()会有问题”-例如,数据绑定。我也有同样的情况。.ToLower()对我不起作用的原因是格式化字符串来自数据库(即,它可由最终用户配置)。我只是建议您编写自己的字符串格式化程序。实际上,您可以从这里开始:,但是还有很多事情要做…在DisplayFormatAttribute的范围内有没有办法做到这一点?如果没有指定格式,将出现
NullReferenceException
,因此应该在
format()
方法中添加空检查条件。