标签:OLE name 详细 oid bool ogr col 字符 操作符
在C#中存在三种比较对象相等性的方法,== ,Equals,以及 ReferenceEquals,对于这三种不同形式的相等性比较,他们又存在着那些差异呢?
在C#中存在着两种比较形式,即引用相等的比较和值相等的比较。对于值类型和引用类型,两者在进行比较时的内容也是不同的。
在默认情况下,对值类型进行数值比较,对引用类型进行引用比较。
有关 == 的使用主要可以分为三种情况:
==
) 返回 true,否则返回 False。 ==
会返回 true。 ==
会比较字符串的值。这是由于 string 是微软封装的一个字符串类,在内部他已经对 == 操作符进行了重写,重写后比较的则是两个变量的内容是否相同。class Test
{ }
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 1;
Test A = new Test();
Test B = A;
string c = "qwer";
string d = "qwer";
Console.WriteLine(a == b);
Console.WriteLine(A == B);
Console.WriteLine(c == d);
Console.WriteLine((2 + 2) == 4);
Console.ReadKey();
}
}
输出结果如下:
True
True
True
True
有关 Equals 的使用主要可以分为三种情况:
,
但必须对 Object 中的 Equals 实现重写
。 class Test
{
string name;
public Test(string name)
{
this.name = name;
}
}
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 1;
Test A = new Test("kyle");
Test B = new Test("kyle");
string c = "qwer";
string d = "qwer";
Console.WriteLine(a.Equals(b));
Console.WriteLine(A.Equals(B));
Console.WriteLine(c.Equals(d));
Console.WriteLine((2+2).Equals(4));
Console.ReadKey();
}
}
输出结果如下:
True
False
True
True
Equals 始终实现的是对值的比较,明显对象 A,B 的值是相等的,但 A.Equals(B) 的输出结果确实 False,这是因为 Equals 是 Object 中的一个虚方法,而 Test 类中没有对其进行重写,因此此时调用的仍是父类中的 Equals 方法。但是父类是无法知道 Test 的成员字段,因此返回的是 false。因此想要比较两个变量的内容是否相同,那就应该重写 Equals 方法。
public override bool Equals(object obj)
{
Person t = obj as Person;
if(this.name == t.name)
{
return true;
}
else
{
return false;
}
}
ReferenceEquals 是 Object 中的静态方法,对于值类型或者引用类型都是用来检查引用是否相同
class Person
{
string name;
public Person(string name)
{
this.name = name;
}
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 1;
Person A = new Person("kyle");
Person B = new Person("kyle");
Person C = B;
Console.WriteLine(ReferenceEquals(a, b));
Console.WriteLine(ReferenceEquals(A, B));
Console.WriteLine(ReferenceEquals(B, C));
Console.ReadKey();
}
}
}
输出结果如下:
False
False
True
相等性比较 (== ,Equals,ReferenceEquals)
标签:OLE name 详细 oid bool ogr col 字符 操作符
原文地址:https://www.cnblogs.com/jizhiqiliao/p/9809380.html