'string'在C#中不包含/ Error的定义

时间:2014-07-21 12:54:09

标签: 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'不包含'AddQueryParam'的定义,不包含   扩展方法'AddQueryParam'接受类型的第一个参数   可以找到'string'(你是否错过了使用指令或者   装配参考?)

我该如何解决这个问题?感谢。

3 个答案:

答案 0 :(得分:3)

要制作扩展方法AddQueryParam,请将其放在单独的静态类中。

static class StringExtension
{
    public static string AddQueryParam(this string source, string key, string value)
    {
        // ...
    }
}

顺便说一句,我希望发布的代码应该给出另一个错误:

  

扩展方法必须在非泛型静态类中定义

答案 1 :(得分:2)

AddQueryParam扩展程序方法。所以你应该将它放在static类中。

static public class Extensions
{
    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);
}

有关扩展程序的详细信息,请查看here

答案 2 :(得分:2)

需要在非泛型静态类中声明Extension Method

来自C# Specification

  

26.2.1声明扩展方法

     

通过在第一个参数上指定关键字this作为修饰符来声明扩展方法   方法。扩展方法只能在非泛型中声明,   非嵌套静态类。以下是静态的示例   声明两种扩展方法的类。

声明如下:

public static class StringExtensions
{
   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);
   }
}