繁体   English   中英

为什么存储在对象变量中并与==进行比较的字符串会有这种奇怪的行为?

[英]Why strings stored in object variables and compared with == have this strange behavior?

比较两个字符串属性与反射的用法时的奇怪行为。

var a = new A
{
    X = "aa",
    B = 1
};

var b = new A
{
    X = "aa",
    B = 2
};

Type type = typeof(A);

object aObjValue = type.GetProperty("X")?.GetValue(a);
object bObjValue = type.GetProperty("X")?.GetValue(b);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

a.X = Console.ReadLine();

aObjValue = type.GetProperty("X")?.GetValue(a);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

a.X = "aa";

aObjValue = type.GetProperty("X")?.GetValue(a);

Console.WriteLine("aObjValue == bObjValue : " + (aObjValue == bObjValue));
Console.WriteLine("aObjValue.Equals(bObjValue) : " + aObjValue.Equals(bObjValue));

Console.ReadKey();

//aObjValue == bObjValue : True
//aObjValue.Equals(bObjValue) : True
//aa
//aObjValue == bObjValue : False
//aObjValue.Equals(bObjValue) : True
//aObjValue == bObjValue : True
//aObjValue.Equals(bObjValue) : True

当使用Console.ReadLine()并将aX手动分配给“ aa”时,我得到了false但是当再次在代码中对其分配时,我得到了true 这对我来说是意外的行为。 有人可以解释一下这是怎么回事吗?

因此,您知道字符串重载了等于运算符==来使用Equals 但是由于将它们存储在Object变量中,因此它们使用的是Object的版本,该版本仅比较引用。

同样,字符串是一种特殊类型,它使用一种称为字符串实习的方法来提高性能。 因此,如果您使用字符串文字"aa"则如果已经存在字符串文字"aa"则不会分配新的内存。 就是这种情况。 这就是为什么第一个aObjValue == bObjValue返回true ,两者都是相同的引用。

在第二种情况下,请在控制台中输入字符串"aa" 这将不使用字符串实习(这是编译器功能),因此它是String全新实例。 这就是为什么第二个aObjValue == bObjValue返回false 如果将它们强制转换为String ,则可以使用==并且可以获得预期的行为(与String.Equals相同)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM