String.Format()--输入字符串的格式不正确

本文关键字:字符串 格式 不正确 输入 Format String | 更新日期: 2023-09-27 18:21:29

String.Format()方法上得到这个错误,不知道为什么,我觉得一切都很好?

string fontface = "";
foreach(...)
{
  fontface = String.Format(@"{3}
    @font-face {
        font-family: '{0}';
        src: url('{0}.eot');
        src: url('{0}.eot') format('embedded-opentype'),
                url('{0}.woff2') format('woff2'),
                url('{0}.woff') format('woff'),
                url('{0}.ttf') format('truetype'),
                url('{0}.svg#{0}') format('svg');
        font-weight:{1};
        font-style:{2};
    }"
  , family, weight, style, fontface);
}

String.Format()--输入字符串的格式不正确

您需要通过将它们加倍来转义"{", "}",因为string.Format()认为每个'{''}'都是占位符(如'{0}')的一部分

类似这样的东西:

fontface = String.Format(@"{3}
    @font-face {{
        font-family: '{0}';
        src: url('{0}.eot');
        src: url('{0}.eot') format('embedded-opentype'),
                url('{0}.woff2') format('woff2'),
                url('{0}.woff') format('woff'),
                url('{0}.ttf') format('truetype'),
                url('{0}.svg#{0}') format('svg');
        font-weight:{1};
        font-style:{2};
    }}"
  , family, weight, style, fontface);

您的两个问题是线路@font-face {}"。使用Format时,必须使用其中两个大括号来转义大括号。只需将其更改为@font-face {{}}" 的行