以下是程序代码,有些地方写得不完善,只能说仅仅说明了问题,不对之处请指教:
using System;
using System.Xml;
namespace ConsoleApplication8
{
/// <summary>
/// 姓名类
/// </summary>
class Namer
{
private string FirstName;
private string LastName;
public Namer()
{
this.Init(null,null);
}
public Namer(string fn,string ln)
{
this.Init(fn,ln);
}
private void Init(string fn,string ln)
{
this.FirstName=fn;
this.LastName=ln;
}
/// <summary>
/// 重载运算符true
/// </summary>
/// <param name="n"></param>
/// <returns>如果姓名中姓或名有一个为空,就返回假</returns>
public static bool operator true(Namer n)
{
if(n.FirstName==null || n.LastName==null)
return false;
else
return true;
}
/// <summary>
/// 重载运算符false
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
public static bool operator false(Namer n)
{
if(n.FirstName==null || n.LastName==null)
return false;
else
return true;
}
/// <summary>
/// 重载运算符==
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static bool operator ==(Namer n1,Namer n2)
{
if(n1.FirstName==n2.FirstName && n1.LastName==n2.LastName)
return true;
else
return false;
}
/// <summary>
/// 重载运算符!=
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static bool operator !=(Namer n1,Namer n2)
{
if(n1.FirstName!=n2.FirstName || n1.LastName !=n2.LastName)
return true;
else
return false;
}
/// <summary>
/// 重载运算符>
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static bool operator >(Namer n1,Namer n2)
{
return (n1.FirstName.CompareTo(n2.FirstName)>0 && n1.LastName.CompareTo(n2.LastName)>0);
}
/// <summary>
/// 重载运算符<
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static bool operator <(Namer n1,Namer n2)
{
return (n1.FirstName.CompareTo(n2.FirstName)<0 && n1.LastName.CompareTo(n2.LastName)<0);
}
/// <summary>
/// 重写方法,必须有,后面的111是乱加的,你也可以写其它的
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode()*111;
}
/// <summary>
/// 重写方法,必须有
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return base.Equals (obj);
}
/// <summary>
/// 重写方法,必须有
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "姓:"+this.FirstName+" 名:"+this.LastName;
}
public static void Main()
{
Namer n1=new Namer("li","zanhong");
Namer n2=new Namer("ahang","aan");
//Namer n2=new Namer("li","zanhong");
if(n1==n2)
Console.WriteLine("一样的名字");
else
Console.WriteLine("不一样的名字");
/////////////////////////////////////
if(n1!=n2)
Console.WriteLine("不一样的名字成立");
else
Console.WriteLine("同样的名字成立");
/////////////////////////////////////
if(n1>n2)
Console.WriteLine(n1.ToString()+">"+n2.ToString());
else if(n1<n2)
Console.WriteLine(n1.ToString()+"<"+n2.ToString());
else
Console.WriteLine("没有正确比较");
Console.ReadLine();
}
}
}