BlogEngine学习一:操作符重载
时间:2011-01-07 来源:程序诗人
先来看看在BlogEngine系统中,操作符的重载方式如下:
/// <summary>
/// Checks to see if two business objects are the same.
/// </summary>
public static bool operator ==(BusinessBase<TYPE, KEY> first, BusinessBase<TYPE, KEY> second)
{
if (Object.ReferenceEquals(first, second))
{
return true;
}
if ((object)first == null || (object)second == null)
{
return false;
}
return first.GetHashCode() == second.GetHashCode();
}
/// <summary>
/// Checks to see if two business objects are different.
/// </summary>
public static bool operator !=(BusinessBase<TYPE, KEY> first, BusinessBase<TYPE, KEY> second)
{
return !(first == second);
}
下面的列表将向你展示在C#语言中,可以进行重载的操作符:
+, -, *, /, %, &, |, <<, >> 所有的C#字节操作符都能够被重载。
+, -, !, ~, ++, –, true, false 所有的C#一元操作符都能够被重载。
==, !=, <, >, <= , >= 所有的C#二元操作符都能够被重载。
&&, || ,=, . , ?:, ->, new, is, as, size of 这些操作符都不能够被重载.
下面就以代码来说明操作符重载的方法:
类TestOperator如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///TestOperator 的摘要说明
/// </summary>
public class TestOperator
{
public int Life; //生命
public TestOperator(int life)
{
this.Life = life;
}
public static TestOperator operator +(TestOperator role1,TestOperator role2)
{
return new TestOperator(role1.Life+role2.Life);
}
public static TestOperator operator +(int _life, TestOperator role2)
{
return new TestOperator(_life) + role2;
}
public static TestOperator operator +(TestOperator role1, int _life)
{
return role1 + new TestOperator(_life);
}
}
然后在前台页面上的使用方式如下:
using System;public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("操作符重载:<br>");
TestOperator life1 = new TestOperator(100);
TestOperator life2 = new TestOperator(200);
TestOperator _result1 = life1 + life2;
Response.Write(_result1.Life);
Response.Write("<br>-----------------------<br>");
TestOperator life11 = new TestOperator(100);
int life22 = 120;
TestOperator _result2 = life11 + life22;
Response.Write(_result2.Life);
Response.Write("<br>-----------------------<br>");
int life111 = 100;
TestOperator life222 = new TestOperator(100);
TestOperator _result3 = life111 + life222;
Response.Write(_result3.Life);
}
}
然后得到的结果如下:
操作符重载:
300
-----------------------
220
-----------------------
200
这样,就简单的实现了操作符的重载,需要说明的是,在实际项目中,操作符的重载可能比这个复杂的多,只要正确的处理就行了.
相关阅读 更多 +