C#试题(一)判断相等的方法和操作符--ReferenceEquels(),Equels(),==

  1. .NET Framework 类库提供了静态方法public static bool ReferenceEquals (
        Object objA,
        Object objB
    )
    确定指定的 Object 实例是否是相同的实例。也就是比较引用类型是否是对同一个对象的引用。
  2. 对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false。对于string 以外的引用类型,如果两个对象引用同一个对象,则 == 返回 true。对于 string 类型,== 比较字符串的值。
    int a = 8;
    int b = 8;
    if (a == b)
    Console.WriteLine("a is equal to b");
  3. Equals 方法有静态和实例两个版本
    object a =  new object();
    object b =  new object();
    if (object.Equals(a, b))
    {}
    a = b;
    if (object.Equals(a, b))
    {}
  4. public overide bool Equals(object obj)
    {}

  5. 几乎所有的引用类型使用Equals,当你比较相等而不是引用identity! String类型是个特例,可以使用==比较相等,这样更易读!
  6. 在项目中大多数是值比较而不是引用比较
  7. 结论**
    引用类型用Equals方法
    值类型用==
 1using System;
 2
 3public class Test
 4{
 5    static void Main()
 6    {
 7        // Create two equal but distinct strings
 8        string a = new string(new char[] {'h''e''l''l''o'});
 9        string b = new string(new char[] {'h''e''l''l''o'});
10        
11        Console.WriteLine (a==b);
12        Console.WriteLine (a.Equals(b));
13        
14        // Now let's see what happens with the same tests but
15        // with variables of type object
16        object c = a;
17        object d = b;
18        
19        Console.WriteLine (c==d);
20        Console.WriteLine (c.Equals(d));
21    }

22}

23The results are: 
24
25True
26True
27False
28True
29

Determines whether the specified Object is equal to the current Object.

http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx
When should I use == and when should I use Equals?

http://msdn2.microsoft.com/zh-cn/library/336aedhh.aspx
实现 Equals 方法

http://msdn2.microsoft.com/en-us/library/336aedhh.aspx
Implementing the Equals Method 


Addition operator +
Subtraction operator -
Equality operator ==

posted @ 2007-09-18 13:49  许晓光  阅读(867)  评论(0编辑  收藏  举报