2010-11-02 22 views
5

== referans karşılaştırma null geldiğinde aynı sınıfın iki örneğini karşılaştırır operatörünü aşırı iyi yöntem nedir null geldiğinde?C#: en iyi uygulama == operatörünü aşırı o referanslar

MyObject o1 = null; 
MyObject o2 = null; 
if (o1 == o2) ... 


static bool operator == (MyClass o1, MyClass o2) 
{ 
    // ooops! this way leads toward recursion with stackoverflow as the result 
    if (o1 == null && o2 == null) 
    return true; 

    // it works! 
    if (Equals(o1, null) && Equals(o2, null)) 
    return true; 

    ... 
} 

Karşılaştırmada boş referansları işlemek için en iyi yaklaşım nedir?

cevap

11

bir "en iyi yaklaşım" olup olmadığını merak ettik.

static bool operator == (MyClass o1, MyClass o2) 
{ 
    if(object.ReferenceEquals(o1, o2)) // This handles if they're both null 
     return true;     // or if it's the same object 

    if(object.ReferenceEquals(o1, null)) 
     return false; 

    if(object.ReferenceEquals(o2, null)) // Is this necessary? See Gabe's comment 
     return false; 

    return o1.Equals(o2); 

} 
+4

'object.ReferenceEquals (o2, null))' onay değil İşte bunun için gereken adımları kesinlikle gerekli. Oranlar, 'Equals''ın yaptığı ilk şey aynı kontrolü yapmaktır. – Gabe

1
if (ReferenceEquals(o1, null) && ReferenceEquals(o2, null)) 
    return true; 

vb