c# - 'string' 不包含 C# 中的/错误定义

标签 c#

我正在尝试在 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/

相关文章:

c# - 你能使 VB.NET 编译像 C# 一样严格吗?

c# - 如何在 c# cake build 中创建任务以使用 FTP 上传文件?

C# Mono 软调试器

c# - 替换多个字段中的多个特殊字符 SQL

c# - 当前上下文中不存在“ session ”

c# - 不在 linq to sql 之间

c# - 由于类型不匹配,无法完成日期时间转换

C#检测页面重定向

C# MongoDB 驱动程序 : Can I use generic type for BsonId?

c# - 针对 10240 的 UWP 应用中的辅助 View 中未调用卸载事件