【问题标题】:String compare returns false eventhough they are the same字符串比较返回 false,即使它们相同
【发布时间】:2014-03-28 13:17:46
【问题描述】:

我有这个代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
using System.Text.RegularExpressions;

namespace SerialTrial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public class ThreadExample
    {
        FlowDocument mcFlowDoc = new FlowDocument();
        Paragraph para = new Paragraph();

        public static void ThreadJob(MainWindow mainWindow)
        {
            string dBConnectionString = @"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\CompanyList.sqlite;";
            SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
            //open connection to database
            try
            {
                sqliteCon.Open();
                SQLiteCommand createCommand = new SQLiteCommand("Select * from AllEmployee", sqliteCon);
                SQLiteDataReader reader;
                reader = createCommand.ExecuteReader();

                int count = 0;
                //richtextbox2.Document.Blocks.Clear();
                List<string> mystring = new List<string>();
                while (reader.Read())
                {
                    count++;
                    string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetString(0))));

                    Console.WriteLine(Text);

                    mystring.Add(Text);
                    if (Convert.ToBoolean(Text))
                    {
                        mystring.Add("1");
                        //string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;

                        //replace two or more consecutive spaces with a single space, and
                        //replace  two or more consecutive newlines with a single newline.
                        //var str = Regex.Replace(myText, @"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
                        //Int64 id = reader.GetInt64(0);
                        string fname = reader.GetString(1);
                        string sname = reader.GetString(2);
                        DateTime saveNow = DateTime.Now;

                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run(saveNow.ToString())))));
                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.AppendText(": ")));
                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.AppendText(fname)));
                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.AppendText(" ")));
                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.AppendText(sname)));
                        mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.AppendText(" granted access to gate 1")));                      
                        string text = "s";
                        mainWindow.WriteSerial(text);
                        //Console.WriteLine(Text);

                        //Console.WriteLine("ID = {0}, Name = {1}, Surname = {2}, Age = {3}", id, fname, sname, age);
                        //Console.WriteLine("{0}\t{1}\t{2}\t{3}", reader.GetInt64(0), reader.GetString(1), reader.GetString(2), reader.GetString(3));

                    }
                }
sqliteCon.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }

public partial class MainWindow : Window
    {
        SerialPort serial = new SerialPort();
        //string received_data;
        //Thread readThread = new Thread(Read);
        FlowDocument mcFlowDoc = new FlowDocument();
        Paragraph para = new Paragraph();


        public MainWindow()
        {
            InitializeComponent();
            combobox1.Items.Insert(0, "Select Port");
            combobox1.SelectedIndex = 0;
            string[] ports = null;
            ports = SerialPort.GetPortNames();


            // Display each port name to the console. 
            int c = ports.Count();
            for (int i = 1; i <= c; i++)
            {
                if (!combobox1.Items.Contains(ports[i - 1]))
                {
                    combobox1.Items.Add(ports[i - 1]);
                }

            }
        }
        string dBConnectionString = @"Data Source = C:\Users\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\CompanyList.sqlite;";

        static int count = 0;

private void Button_Click(object sender, RoutedEventArgs e)
        {
            count++;
            string[] ports = null;
            ports = SerialPort.GetPortNames();


            // Display each port name to the console. 
            int c = ports.Count();
            for (int i = 1; i <= c; i++)
            {
                if (!combobox1.Items.Contains(ports[i - 1]))
                {
                    combobox1.Items.Add(ports[i - 1]);
                }

            }

        }
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {   
            int bytes = serial.BytesToRead;
            Console.WriteLine(bytes);
            if (bytes == 14)
            {
                byte[] buffer = new byte[bytes];
                serial.Read(buffer, 0, bytes);
                System.String ID = System.Text.Encoding.Default.GetString(buffer);
                //System.String ID = new String(System.Text.Encoding.UTF8.GetChars(buffer));
                Console.WriteLine(ID);
                foreach (var item in ID)
                {
                    Console.WriteLine(item.ToString());
                }
                /*
                Console.WriteLine();
                string s2 = BitConverter.ToString(buffer);
                string tempAry = s2.Replace("-", "");
                Console.WriteLine(tempAry);

                Variables.buffering = BitConverter.ToInt64(buffer, 0);
                 */
                Variables.buffering = ID;
                Console.WriteLine();
                //Console.WriteLine(Variables.buffering);
                Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));
                thread.Start();
                thread.Join();
            }

        }

我在相当于 70002B408E95 的串口中发送 0x02,0x37,0x30,0x30,0x30,0x32,0x42,0x34,0x30,0x38,0x45,0x39,0x35,0x03。这个 ID 代码在我的数据库中也是 70002B408E95。为什么我的 compare.Equals 虽然两个字符串都是真的却返回假?

Variables.buffering 在我的课程中用于使缓冲成为全局。

class Variables
    {
        public static System.String buffering;

    }

请帮忙。谢谢

【问题讨论】:

  • 您的代码中哪里出现了错误?你提供了很多代码……你试过调试检查器告诉你什么吗?
  • 要支持您相对简单的问题,需要大量代码。您是否尝试过显示相同问题的非常小的控制台应用程序?
  • 当您调用Object.Equals 时,Variables.bufferingreader.GetString(0) 的内容究竟是什么? .ToCharArray() 有什么输出?他们持有什么?另外:你应该在这里使用==Variables.buffering == reader.GetString(0)
  • 您将开头的 0x02 和结尾的 0x03 也转换为字符串。如果您转换为字符串,您会想跳过它们。试试.GetString(buffer, 1, 12)
  • Variables.buffering 在一个类中使其成为全局。没有错误,但输出不是我所期望的,因为我从串行接收的字符串在数据库中是相同的。我的代码如何返回错误?这段代码是:string Text = (String.Format("{0}", Object.Equals(Variables.buffering, reader.GetString(0))));

标签: c# sqlite


【解决方案1】:

您收到0x02,0x37,0x30,0x30,0x30,0x32,0x42,0x34,0x30,0x38,0x45,0x39,0x35,0x03 作为您的数据。我猜 0x020x03 是一种 startstop 字节。它们之间是你的 ASCII 字符串。因此,您需要通过替换代码来忽略这些 startstop 字节:

System.String ID = System.Text.Encoding.Default.GetString(buffer);

System.String ID = System.Text.Encoding.Default.GetString(buffer, 1, 12); // start reading from byte at 1st position and take 12 of them

【讨论】:

    【解决方案2】:

    通常我们比较值类型变量或引用类型变量。如果您将 int,string 类型的变量与 int,string 进行比较,那么您应该选择像 1=1 或 "a"="b" 这样的值类型,但是当您与 object 比较时,您应该选择像 1.equal 这样的引用类型(1) 或 a.equal(b)

    【讨论】:

      【解决方案3】:

      Object.Equals 比较地址

          Object.Equals(Variables.buffering, reader.GetString(0))
      

      尝试使用 String.Equals 来比较字符串

      编辑:正如下面的 cmets 所指出的,这不仅不起作用,而且也是错误的,所以请忽略我的回答

      【讨论】:

      • 我尝试改成这个:string Text = (String.Format("{0}", String.Equals(Variables.buffering, reader.GetString(0)))); ---- 但它仍然返回 false
      • 如果你将 Object.Equals 与字符串一起使用,它将调用 string.Equals
      • 那么我将如何检查两个字符串的相似性?一个来自串口,另一个来自我的sqlite数据库
      • 如上建议的 Variables.buffering == reader.GetString(0) 怎么样?
      • object.Equals 比较地址。它执行覆盖的Equals 方法对提供的第一个实例所做的任何事情。引用类型的默认实现是比较引用,但只有在没有提供其他实现时才会这样做。字符串覆盖Equals 以提供值语义。
      猜你喜欢
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多