【问题标题】:Error message "Cannot implicitly convert type 'String' to 'Int'" [closed]错误消息“无法将类型'String'隐式转换为'Int'”[关闭]
【发布时间】:2016-06-27 05:19:18
【问题描述】:

我不断收到调试错误“无法将类型 'string' 隐式转换为 '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();但是错误.......

【问题讨论】:

    标签: c# asp.net httpcookie


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢兄弟。是的,没错,这就是我脑海中出现的关于字符串到 int 的问题............ !!
    【解决方案2】:

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

    您实际上是在尝试通过index 从array 访问element,而您正在通过name 访问它,这会引发错误。

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

    【讨论】:

    • 谢谢兄弟............ !!
    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2022-08-17
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多