C# 转换关键字:operator、explicit与implicit
operator 关键字用于在类或结构声明中声明运算符。运算符声明可以采用下列四种形式之一:
public static result-type operator unary-operator ( op-type operand )
public static result-type operator binary-operator (
op-type operand,
op-type2 operand2
)
public static implicit operator conv-type-out ( conv-type-in operand )
public static explicit operator conv-type-out ( conv-type-in operand )
参数说明
result-type
运算符的结果类型。
unary-operator
下列运算符之一:+ - ! ~ ++ — true false
op-type
第一个(或唯一一个)参数的类型。
operand
第一个(或唯一一个)参数的名称。
binary-operator
其中一个:+ - * / % & | ^ << >> == != > < >= <=
op-type2
第二个参数的类型。
operand2
第二个参数的名称。
conv-type-out
类型转换运算符的目标类型。
conv-type-in
类型转换运算符的输入类型。
代码举例
public static RMB operator +(RMB rmb1, RMB rmb2)
{
return new RMB(rmb1.Yuan + rmb2.Yuan, rmb1.Jiao + rmb2.Jiao, rmb1.Fen + rmb2.Fen);
}
public static implicit operator float(RMB rmb)
{
return rmb.Yuan + (rmb.Jiao/10.0f) + (rmb.Fen/100.00f);
}
public static explicit operator RMB(float f)
{
uint yuan = (uint)f;
uint jiao = (uint)((f - yuan) * 10);
uint fen = (uint)(((f - yuan) * 100) % 10);
return new RMB(yuan, jiao, fen);
}
调用:
RMB r1,r2,r3;
……//略new过程
r3 = r1+r2;
float f = r1;// 隐式转换
Console.WriteLine("float f= {0}", f);
r2 = (RMB)f;// 显式转换
Console.WriteLine("r2 = {0}", r2.ToString());
部分引自:http://www.cnblogs.com/hunts/archive/2007/01/17/operator_explicit_implicit.html