Operator运算符重载与Implicit隐式类型转换

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);  
    }  
}  

你可能感兴趣的:(C#)