【问题标题】:Default parameter value for 'postData' must be a compile-time constant“postData”的默认参数值必须是编译时常量
【发布时间】:2015-10-07 08:20:02
【问题描述】:

我想使用控制台应用程序登录 MyBB 论坛,但我的代码出现错误

'postData' 的默认参数值必须是编译时常量

如果我将我的用户名和密码设置为 const 字符串,我可以很容易地修复它,但我不能使用 Console.ReadLine();所以我不得不硬编码用户名和密码,我认为这不是一个好主意。

这是我的代码:

        public  string Username = Console.ReadLine();
    public  string Password = Console.ReadLine();
    public const string ForumUrl = "forum.smurfbot.net";

    static void Main(string[] args)
    {

    }

    public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login")
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = true;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = true;

        byte[] postBytes = Encoding.ASCII.GetBytes(postData);
        request.ContentLength = postBytes.Length;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        string sReturn = sr.ReadToEnd();
        sr.Dispose();

        return sReturn;
    }

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    为什么首先要为它设置一个默认值?这不是函数的工作方式!

    使用单独的参数并在函数内执行字符串连接。

    public string MakePostRequest(string url, string Username, string Password, string ForumUrl)
    {
        string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login"
        ...
    }
    

    对于像“MakePostRequest”这样具有默认 URL 或默认 POST 数据的通用名称的方法听起来很奇怪。

    说实话,我希望它只接受一个 URL 和一个 POST 数据的映射,然后由调用者为该请求传递正确的数据。

    【讨论】:

      【解决方案2】:

      C# 允许设置常量以外的默认值,因此您不能使用字段/其他参数。对于url 来说没关系,因为这是一个常数值。不允许使用 postData 的串联字符串。

      一个选项是将默认设置为null,并在您的方法中检查它。 允许的:

      public string MakePostRequest(string url = "www.website.com/usercp.php", string postData = null)
      {
          if (string.IsNullOrEmpty(postData))
          {
              postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login";
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-07
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多