为什么String.Equals返回false?
我有以下C#代码(来自我正在使用的库),该代码试图查找比较指纹的证书。请注意,在以下代码中, mycert.Thumbprint
和 certificateThumbprint
都是字符串。
I have the following C# code (from a library I'm using) that tries to find a certificate comparing the thumbprint. Notice that in the following code both mycert.Thumbprint
and certificateThumbprint
are strings.
var certificateThumbprint = AppSettings.CertificateThumbprint;
var cert =
myStore.Certificates.OfType<X509Certificate2>().FirstOrDefault(
mycert =>
mycert.Thumbprint != null && mycert.Thumbprint.Equals(certificateThumbprint)
);
这无法找到带有指纹的证书,因为 mycert.Thumbprint.Equals (certificateThumbprint)
是 false
,即使字符串相等。 mycert.Thumbprint == certificateThumbprint
也会返回 false
,而 mycert.Thumbprint.CompareTo(certificateThumbprint )
返回0。
This fails to find the certificate with the thumbprint because mycert.Thumbprint.Equals(certificateThumbprint)
is false
even when the strings are equal. mycert.Thumbprint == certificateThumbprint
also returns false
, while mycert.Thumbprint.CompareTo(certificateThumbprint)
returns 0.
我可能遗漏了一些明显的内容,但我不知道为什么等于
方法失败。
I might be missing something obvious, but I can't figure out why the Equals
method is failing. Ideas?
比较要忽略某些字符:
static void Main(string[] args)
{
var a = "asdas"+(char)847;//add a hidden character
var b = "asdas";
Console.WriteLine(a.Equals(b)); //false
Console.WriteLine(a.CompareTo(b)); //0
Console.WriteLine(a.Length); //6
Console.WriteLine(b.Length); //5
//watch window shows both a and b as "asdas"
}
(在这里,添加到 a
的字符是 U + 034F
,组合了Grapheme Joiner 。)
(Here, the character added to a
is U+034F
, Combining Grapheme Joiner.)
因此,CompareTo的结果不能很好地表明Equals中存在错误。您出现问题的最可能原因是隐藏字符。您可以检查长度以确保确定。
So CompareTo's result is not a good indicator of a bug in Equals. The most likely reason of your problem is hidden characters. You can check the lengths to be sure.
请参见此以获取更多信息。
See this for more info.