本文介绍了比较类型的VALUE和REFERENCE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在C#中有很多方法可以比较VALUE和REFERENCES,但是当您尝试比较VALUE或REFERENCE时,我仍然对哪种类型的性能感到困惑.

I know there are a lot of ways to compare VALUE and REFERENCES in C#, but I'm still a bit confused about what type performs what when you try to compare either VALUE or REFERENCE.

字符串示例:

string str = "hello";
string str2 = "hello";

if (str == str2)
{
   Console.WriteLine("Something");
} // Is this a comparison of value?

if (str.Equals(str2))
{
   Console.WriteLine("Something");
} // Is this a comparison of value?

string.ReferenceEquals(str, str2); // Comparison of reference (True)

Console.WriteLine((object)str1 == (object)str2); // Comparison of reference (True)

推荐答案

Equals==如果未在子类中覆盖/重载,则默认情况下将通过引用进行比较. ReferenceEquals将始终通过引用进行比较.

Equals and == will compare by reference by default if they're not overriden / overloaded in a subclass. ReferenceEquals will always compare by reference.

字符串是一种令人困惑的数据类型,可用于进行此实验,因为它们重载了==来实现值相等.同样,由于它们是不可变的,因此C#通常会将相同的实例重用于相同的文字字符串.在您的代码中,strstr2将是同一对象.

Strings are a confusing data type to use for experimenting with this, because they overload == to implement value equality; also, since they're immutable, C# will generally reuse the same instance for the same literal string. In your code, str and str2 will be the same object.

这篇关于比较类型的VALUE和REFERENCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 10:52