postData'必须是编译时常数

本文关键字:编译 常数 postData | 更新日期: 2023-09-27 18:16:19

我想登录到我的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;
    }

postData'必须是编译时常数

为什么要设置一个默认值呢?函数不是这样工作的!

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

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数据,这听起来很奇怪。

老实说,我希望它只接受POST数据的URL和映射,然后由调用者为该请求传递适当的数据。

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