错误信息"无法隐式转换类型'字符串'到' Int'"

时间:2016-06-27 05:19:18

标签: c# asp.net httpcookie

我一直收到调试错误"无法隐式转换类型' 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");
    }

我也将它改为新的HttpCookie [" UserInfo"]。ToString();但错误.......

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

您实际上是尝试element array之前的index访问intname并且您正在HttpCookie httpCookie = new HttpCookie("UserInfo"); httpCookie.Values.Add("Name", NameTextBox.Text); httpCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(httpCookie); 访问arg1.startsWith(' '),这会引发错误

bool stringDoesStartWithWhitespace = false;
if (!arg1.isEmpty()) {
    stringDoesStartWithWhitespace = arg1[0].isSpace();
}