Human类中实现了Human与Int String类型的转型,虽然从这个例子体现不出这种类型转换的好处,这只是演示一下实现过程而已,在软件的设计过程中对类型转换处理会带来更精妙的作用的。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace GraceCode
{
class 转换操作符以及操作符方法
{
}
internal sealed class Human
{
private int iSum = 12;
private string[] strTmp = new string[3] {"1","2","3" };
[IndexerName("Test")]
public string this[int iIndex]
{
get
{
return strTmp[iIndex];
}
protected set
{
strTmp[iIndex] = value;
}
}
public Human(int i)
{
iSum = i;
}
public int ToInt32()
{
return this.iSum;
}
public string ToString()
{
return iSum.ToString();
}
public static implicit operator String(Human h)
{
return h.ToString();
}
public static implicit operator Human(int i)
{
return new Human(i);
}
public static explicit operator Int32(Human i)
{
return i.ToInt32();
}
public static Human operator +(Human h1, Human h2)
{
return new Human(h1.iSum + h2.iSum);
}
}
}
===========================================================
Human使用的部分代码
Human h1 = 10;
Console.WriteLine(h1);
Human h2 = 20;Console.WriteLine(h2);
Human hAll = h1 + h2;
Console.WriteLine(hAll);
Console.Read();