【问题标题】:Operator '==' cannot be applied to operands of type string and char [duplicate]运算符'=='不能应用于字符串和字符类型的操作数[重复]
【发布时间】:2017-04-10 04:10:59
【问题描述】:

我正在使用char,但我很困惑,因为我知道我必须将此char 转换为string 数据类型。

else if (mode.Equals("Update"))
        {
            char id = char.Parse(txtuserId.Text.ToString()); //conversion as i told before

            string newName = txtname.Text;
            string newemail = txtemail.Text;
            string newpassword = txtpassword.Text;
            string newaddress = rtbaddress.Text;
            string newphoneNumber = txtphoneNumber.Text;
            string newroleName = cmbrole.Text;

            users updatedusers = (
                from x in db.users
                where x.id==id // THE WRONG ONE
                select x
                ).First();
        }

【问题讨论】:

  • 尝试在 x.id 中添加 .tostring
  • 字符串id =txtuserId.Text;
  • 表中id的列类型是什么users
  • @EarvinNillCastillo:x.id.ToString = id 在哪里?仍然错误..
  • @ManishSingh 如果我使用字符串 id =txtuserId.Text,表中的数据必须是字符串。但要求是字符..

标签: c# string char type-conversion


【解决方案1】:

我根据评论回答问题

@un-lucky : 数据类型为 char(5);

这意味着该列能够存储长度为 5 的字符数组,现在考虑该输入,即 txtuserId.Text。它本身是一个字符串,因为我们已经知道字符串是一个字符数组,所以你不需要使用char.Parse转换它,你可以直接比较它们。因此,在这种情况下,where 子句将是 where x.id==txtuserId.Text

补充说明: 您无需使用char.Parse 从字符串中获取字符,而是可以使用索引从字符串中的特定位置获取字符。考虑到您想从字符串中获取第一个字符,在这种情况下,您可以像下面这样使用:

if(string.IsNullOrEmpty(txtuserId.Text))
  char firstChar = txtuserId.Text[0];

【讨论】:

    【解决方案2】:

    可以从字符串中解析一个字符,但不能将具有多个字符的字符串解析为字符。这应该是个案情况。

    如果我猜想的 txtuserId 是一个文本框,它的长度仅限于一个字符,则可以使用

    char id = char.Parse(txtuserId.Text.ToString());`
    


    如果 txtuserID 不限于一个字符,您可以使用以下代码: (通过索引获取你想要的字符)

    char[] id = txtuserId.Text.ToCharArray();
    char mID = id[n]
    


    但在你的情况下,我想这不是你所需要的。你在你的代码中是多余的。如果字符串是代码底部的类似 SQL 的代码所需要的,则不要将其转换为 char 数组,然后将其转换为字符串。我建议你这样做:

    else if (mode.Equals("Update"))
            {
                String id= txtuserId.Text; // change this part
    
                string newName = txtname.Text;
                string newemail = txtemail.Text;
                string newpassword = txtpassword.Text;
                string newaddress = rtbaddress.Text;
                string newphoneNumber = txtphoneNumber.Text;
                string newroleName = cmbrole.Text;
    
                users updatedusers = (
                    from x in db.users
                    where x.id==id // leave it as it is
                    select x
                    ).First();
            }
    

    在这段代码中,您不会感到困惑,因为字符串没有被重新转换,而是被正确放置在它应该在的位置。

    【讨论】:

    • 感谢您的建议
    猜你喜欢
    • 2016-06-30
    • 2015-04-19
    • 1970-01-01
    • 2017-10-12
    • 2015-09-10
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多