Operator運算子過載與Implicit隱式型別轉換

世紀緣發表於2016-08-19

class Person

{  
    public int Age { get; set; }  
    public string Name { get; set; }  

    public static int operator -(Person p1, Person p2)//int為想減結果型別,-表示對-進行運算子過載  
        //引數為待計算的兩個值  
    {  
                 return p1.Age - p2.Age;  
    }  

//當過載>後,要求必須過載<
public static bool operator >(Person p1, Person p2)
{
return p1.Age > p2.Age;
}

    public static bool operator <(Person p1, Person p2)  
    {  
        return p1.Age < p2.Age;  
    }  

//將string 轉換成Person
public static implicit operator Person(string s)
{
Person p = new Person();
p.Name = s;
return p;
}
//將Person 轉換成string
public static implicit operator string(Person p)
{
return p.Name;
}

//當過載==後,要求必須過載!=

    public static bool operator ==(Person p1, Person p2)  
    {  
        return p1.Name == p2.Name && p1.Age == p2.Age;  
    }  

    public static bool operator !=(Person p1, Person p2)  
    {  
        return !(p1 == p2);  
    }  
}  

相關文章