繁体   English   中英

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

[英]'string' does not contain a definition for/ Error in 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'的第一个参数(您是否缺少using指令或程序集引用?)

我怎么解决这个问题? 谢谢。

要创建扩展方法AddQueryParam ,请将其放入单独的静态类中。

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

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

扩展方法必须在非通用静态类中定义

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);
}

有关扩展方法的更多信息,请在此处查看

Extension Method需要在非通用的静态类中声明。

C#规范

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);
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM