[英]why when char data equals object data, Equals() evaluates to false?
Consider the following snippet: 考虑以下代码段:
char ch = '[';
string d = "[";
Console.WriteLine(ch.Equals(d))
Output will be false
. 输出将为
false
。
What do you do when you want it to be true
? 当您希望它成为
true
时,您会怎么做?
Edit: 编辑:
variable d
is a string in the example, but in practice it can be any object... 在示例中变量
d
是一个字符串,但实际上它可以是任何对象...
使用ToString();
var result = '['.ToString().Equals("[");
What do you do when you want it to be true?
当您希望它成为真实的时,您会怎么做?
Convert your char
ch to string using ch.ToString
使用
ch.ToString
将您的char
转换为字符串
Console.WriteLine(ch.ToString().Equals(d));
Or Convert string to char using Convert.ToChar
或使用
Convert.ToChar
将字符串转换为char
Console.WriteLine(ch.Equals(Convert.ToChar(d)));
But the above would fail if your string contains more than one character. 但是,如果您的字符串包含多个字符,则上述操作将失败。
EDIT: 编辑:
variable d is a string in the example, but in practice it can be any object...
在示例中变量d是一个字符串,但实际上它可以是任何对象...
Then it would be better to use Convert.ToChar(object)
method to convert the object to character and then compare for equality. 然后最好使用
Convert.ToChar(object)
方法将对象转换为字符,然后进行相等性比较。
string d = "[";
char ch = '[';
object o = (object)d;
Console.WriteLine(ch.Equals(Convert.ToChar(o)));
The above could throw an exception if the object
is not convertible to char
, to be on the safe side you can use char.TryParse
like: 如果
object
不能转换为char
,则上面的方法可能会引发异常,为了安全起见,可以使用char.TryParse
例如:
string d = "[";
char ch = '[';
object obj = (object)d;
char temp;
bool result = obj != null &&
char.TryParse(obj.ToString(), out temp) &&
ch == temp; //same as ch.Equals(temp);
This would return false, if the conversion to character is not successful. 如果无法成功转换为字符,则返回false。
It depends on what you intend. 这取决于您的打算。 Either this
要么这个
Console.WriteLine(ch.Equals(d[0]));
or that 或者那个
Console.WriteLine(ch.ToString().Equals(d));
If d
could be any object (like you added), you could try to use d.ToString()
as well. 如果
d
可以是任何对象(如您添加的对象),则也可以尝试使用d.ToString()
。 But what sense does it make to compare a char
to a slider? 但是将
char
与滑块进行比较有什么意义呢? Depending on the actual type of the object the comparison could become True accidentally. 根据对象的实际类型,比较可能会偶然变为True。
More generally: 更普遍:
char ch = '[';
string d = "[";
bool areEqual = (d != null) && (d.Length == 1) && (d[0].Equals(ch));
Assuming you don't want it to be true when comparing null or "[XXX" with '['. 假设在将null或“ [XXX””与“ [”进行比较时,您不希望它为true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.