我正在尝试在 C# 中创建一个查询字符串。我在 StackOverflow 中找到了这段代码,我非常喜欢它并想在我的项目中使用它。但是我得到一个错误,我坚持下去。这是代码
public static string AddQueryParam(this string source, string key, string value)
{
string delim;
if ((source == null) || !source.Contains("?"))
{
delim = "?";
}
else if (source.EndsWith("?") || source.EndsWith("&"))
{
delim = string.Empty;
}
else
{
delim = "&";
}
return source + delim + HttpUtility.UrlEncode(key)
+ "=" + HttpUtility.UrlEncode(value);
}
private string QueryStringCreator()
{
string queryString = "http://www.something.com/something.html"
.AddQueryParam("name", "jason")//I get the error here
.AddQueryParam("age","26");
return queryString;
}
错误是:
'string' does not contain a definition for 'AddQueryParam' and no extension method 'AddQueryParam' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
我该如何解决这个问题?谢谢。
最佳答案
要制作扩展方法 AddQueryParam
,请将其放入单独的静态类中。
static class StringExtension
{
public static string AddQueryParam(this string source, string key, string value)
{
// ...
}
}
顺便说一句,我希望发布的代码会给出另一个错误:
Extension method must be defined in a non-generic static class
关于c# - 'string' 不包含 C# 中的/错误定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24865628/