- 转换运算符定义了一种从一个类类型到另外一个类类型的转换
- 隐式转换自动调用,显式转换需要通过一个强制转换来调用
- 隐式转换只用于不会发生错误的情况
- 不能发生丢失信息(截断、溢出、或丢失符号等)
- 转换不会抛出异常
- 使用转换运算符的限制
- 不能创建内建的转换。例如,不可以重定义从double到int的转换。
- 不能定义源类型或目标类型是object的转换
- 不能对源或目标类型同时进行implicit和explicit的转换
- 不能定义一个从基类到派生类的转换
- 不能定义源类型或目标类型是一个接口的转换
- 使用方法:
public static operator implicit target-type(source-type v) { return value; }
public static operator explicit target-type(source-type v) { return value; }
- 代码
using System;
namespace Convert
{
class ThreeD
{
int x, y, z;
public ThreeD()
{
x = y = z = 0;
}
public ThreeD(int a, int b, int c)
{
this.x = a;
this.y = b;
this.z = c;
}
public static ThreeD operator +(ThreeD d1,ThreeD d2)
{
ThreeD result = new ThreeD();
result.x = d1.x + d2.x;
result.y = d1.y + d2.y;
result.z = d1.z + d2.z;
return result;
}
public static implicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
public void show()
{
Console.WriteLine(x +"," + y + ","+z);
}
}
class Class1
{
static void Main(string[] args)
{
ThreeD a = new ThreeD(1,2,3);
ThreeD b = new ThreeD(10,10,10);
ThreeD c = new ThreeD();
int i;
a.show();
b.show();
//将A和B相加
c = a + b;
c.show();
//转化为int
i = a;
Console.WriteLine("Result of i = a :" + i);
//转化为int
i = a * 2 -b;
Console.WriteLine("Result of i = a * 2 - b :" + i);
}
}
} -
using System;
namespace Convert
{
class ThreeD
{
int x, y, z;
public ThreeD()
{
x = y = z = 0;
}
public ThreeD(int a, int b, int c)
{
this.x = a;
this.y = b;
this.z = c;
}
public static ThreeD operator +(ThreeD d1,ThreeD d2)
{
ThreeD result = new ThreeD();
result.x = d1.x + d2.x;
result.y = d1.y + d2.y;
result.z = d1.z + d2.z;
return result;
}
public static explicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
public void show()
{
Console.WriteLine(x +"," + y + ","+z);
}
}
class Class1
{
static void Main(string[] args)
{
ThreeD a = new ThreeD(1,2,3);
ThreeD b = new ThreeD(10,10,10);
ThreeD c = new ThreeD();
int i;
a.show();
b.show();
//将A和B相加
c = a + b;
c.show();
//转化为int,必须使用强制
i = (int)a;
Console.WriteLine("Result of i = a :" + i);
//转化为int,必须使用强制
i = (int)a * 2 -(int)b;
Console.WriteLine("Result of i = a * 2 - b :" + i);
}
}
}