using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*使用explicit(显式)和implicit(隐式)*/
namespace 自定义转换
{
class LimitedInt
{
const int MaxValue = 100;
const int MinValue = 0;
private int _TheValue = 0;
public int TheValue
{
get { return _TheValue; }
set
{
if (value < MinValue)
_TheValue = 0;
else
_TheValue = value > MaxValue ? MaxValue : value;
}
}
//隐式转换,自定义的LimitedInt类型转换为int类型
public static implicit operator int(LimitedInt li)
{
return li.TheValue;
}
//隐式转换,int类型转换为自定义的LimitedInt类型
public static implicit operator LimitedInt(int x)
{
LimitedInt li = new LimitedInt();
li.TheValue = x;
return li;
}
//重载运算符取负值-
public static LimitedInt operator -(LimitedInt x)
{
LimitedInt li = new LimitedInt();
li.TheValue = 0;
return li;
}
//重载运算符做减法x-y
public static LimitedInt operator -(LimitedInt x, LimitedInt y)
{
LimitedInt li = new LimitedInt();
li.TheValue = x.TheValue - y.TheValue;
return li;
}
//重载运算符做加法x+y
public static LimitedInt operator +(LimitedInt x, LimitedInt y)
{
LimitedInt li = new LimitedInt();
li.TheValue = x.TheValue + y.TheValue;
return li;
}
}
class Program
{
static void Main(string[] args)
{
LimitedInt li = 5;//将5转换为limitedInt
int Five = li;//将LimitedInt转换为int
Console.WriteLine("li:{0},Five:{1}",li.TheValue,Five);
LimitedInt li1 = 8;
LimitedInt li2 = 10;
Console.WriteLine("li:{0},Five:{1}", li.TheValue, Five);
LimitedInt li3 =li1+li2;
Console.WriteLine("li2+li1={0}", li3.TheValue);
li3=li2-li1;
Console.WriteLine("li2-li1={0}",li3.TheValue);
li3 = -li1;
Console.WriteLine("-li1={0}",li3.TheValue);
Console.ReadKey();
}
}
}