2012-02-23 73 views
1

我比较2个字符串和2个类对象,然后为什么字符串一个比较给出结果“真”,而对象比较给出“假”?请解释两种情况下存储位置的变化情况?字符串和类都是引用类型,那么为什么比较返回不同的结果?

class Program 
{ 
    public class Person 
    { 
     public string Name { get; set; } 
    } 

    static void Main(string[] args) 
    { 
     string s1 = "xyz"; 
     string s2 = "xyz"; 

     bool b = s1 == s2; 

     Person p1 = new Person(); 
     Person p2 = new Person(); 

     bool x = p1 == p2; 

    } 
} 

回答

0

明确的解释。

0

总之,等号运算符的功能是不同的。基本上,对于一个字符串,==运算符会查看每个字符,如果它匹配,并且对于一般的引用类型,==运算符将会看到它们是否具有相同的“指针”。

0

你需要重载==!=运营商为您Person类,如果你想要的东西比引用类型的默认行为(这是返回True当且仅当实例是相同的(except for the string class))其他:

public class Person 
{ 

    public static bool operator ==(Person p1, Person p2) 
    { 
     // Insert logic here 
    } 

    public static bool operator !=(Person p1, Person p2) 
    { 
     // Insert logic here 
    } 
} 

在您的例子,当你实例化两个不同的Person对象,p1 == p2将返回false。

相关问题