错误消息 "Cannot implicitly convert type 'String' to 'Int'"

Error message "Cannot implicitly convert type 'String' to 'Int'"

我一直收到调试错误 "cannot implicitly convert type 'string' to 'int'"。

我将出现错误的文本加粗。

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie httpCookie = Request.Cookies["UserInfo"];

        if (httpCookie == null)
        {
            txtDiv.Visible = true;
        }
        else
        {
            msgDiv.Visible = true;
            string userName = httpCookie.Values["Name"].ToString();
            WelcomeLabel.Text = "Welcome Back Mr. "+userName;
        }
    }

    protected void SignupButton_Click(object sender, EventArgs e)
    {
        // Error in Below Line.
        HttpCookie httpCookie = new HttpCookie["UserInfo"];
        httpCookie.Values.Add("Name", NameTextBox.Text);
        httpCookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(httpCookie);

        Response.Redirect("Thanks.aspx?name="+NameTextBox.Text);
        // Server.Transfer("Thanks.aspx");
    }

我也改成new HttpCookie["UserInfo"].ToString();但是错误......

HttpCookie httpCookie = new HttpCookie["UserInfo"];更改为HttpCookie httpCookie = new HttpCookie("UserInfo");

您实际上是在尝试通过 indexarray 访问 element,这应该是 int 而您正在通过 name 访问它抛出错误。

HttpCookie httpCookie = new HttpCookie("UserInfo");
httpCookie.Values.Add("Name", NameTextBox.Text);
httpCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(httpCookie);

HttpCookie httpCookie = new HttpCookie["UserInfo"];更改为HttpCookie httpCookie = new HttpCookie("UserInfo");

但是出现'string'到'int'错误的原因是因为[]用于数组的索引,[int]。所以它试图将一个字符串转换为一个整数。