日期:2013-03-03  浏览次数:20493 次

C#中奇妙的操作符重载



细心的朋友可能发现,C#虽然可以重载操作符,但和C++比较起来,却有很大的不同。定义的时候重载操作符方法必须是static,而且至少有一个参数(一目和二目分别是一个和两个),C#和C++比起来,最重要的特征是:<、>;==、!=;true、false必须成对出现,即重载了“<”就必须重载“>”,重载了“==”就必须重载“!=”,重载了“true”就必须重载“false”;另外,还必须实现基类object的两个虚方法:GetHashCode()和Equals(object obj)。



以下是程序代码,有些地方写得不完善,只能说仅仅说明了问题,不对之处请指教:

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>

/// 重载运算符<

/// <