C# System.FormatException: 输入字符串的格式不正确

C# System.FormatException: Input string was not in a correct format

我正在尝试使用 String.Format 创建一个字符串并添加参数。但出于某种原因,我收到错误 -

System.FormatException: Input string was not in a correct format.

这是我的代码

string queryPattern =
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX db: <http://dbpedia.org/ontology/> " +
"PREFIX prop: < http://dbpedia.org/property/> " +
"SELECT ?movieLink ?title ?genreLink ?genre ?releaseDate " +
"WHERE { " +
    "?movieLink rdf:type db:Film; " +
                "foaf:name ?title. " +
    "OPTIONAL { ?movieLink prop:genre ?genreLink. " +
                "?genreLink rdfs:label ?genre. " +
                "FILTER(lang(?genre) = 'en') }. " +
    "OPTIONAL{ ?movieLink <http://dbpedia.org/ontology/releaseDate> ?releaseDate }. " +

    "{0}" +
    "{1}" +
    "FILTER(lang(?title) = 'en') " +
"}" +
"ORDER BY DESC(?releaseDate)" +
"{2}";

return String.Format(queryPattern, genreMatch, dateMatch, limit);

如有任何帮助,我们将不胜感激。

string.Format 使用花括号 ({}) 来指示占位符。您的格式字符串无效,因为它包含另外几个花括号。

您需要将这些大括号加倍以转义它们:

string s = "Teststring {{ {0} }}";
string r = string.Format(s, 42);

在 r 中的结果:

Teststring { 42 }

例如你的台词

"WHERE { " +

应该是

"WHERE {{ " +

除占位符外,您不得在格式字符串中使用花括号,因此“{0}”可以,“{some text}”则不行。 您可以使用双花括号解决您的问题:"{{some text}}"

不确定您是如何将值传递给参数的。您可以直接在字符串中使用参数,而不是使用字符串格式化函数。

string queryPattern =
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " +
"PREFIX db: <http://dbpedia.org/ontology/> " +
"PREFIX prop: < http://dbpedia.org/property/> " +
"SELECT ?movieLink ?title ?genreLink ?genre ?releaseDate " +
"WHERE { " +
"?movieLink rdf:type db:Film; " +
            "foaf:name ?title. " +
"OPTIONAL { ?movieLink prop:genre ?genreLink. " +
            "?genreLink rdfs:label ?genre. " +
            "FILTER(lang(?genre) = 'en') }. " +
"OPTIONAL{ ?movieLink <http://dbpedia.org/ontology/releaseDate> ?releaseDate              }. " +

genreMatch +
dateMatch +
"FILTER(lang(?title) = 'en') " +
"}" +
"ORDER BY DESC(?releaseDate)" +
limit;

return queryPattern;