少有人走的路

勇哥的工业自动化技术网站

C#中的转换关键字:explicit、implicit与operator

这个3个关键字貌似不是很常用。C#语法跟Java很接近,但是在Java里面也没有这些关键字。我在网上搜罗了一些资料,希望能够帮助我们更好的理解这些关键字。

MSDN资料:http://msdn.microsoft.com/zh-cn/library/39bb81c3.aspx

首先,explicit和implicit关键字分别表示显式的类型转换和隐式的类型转换。

explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换。
explicit 表示显式转换,如从 A -> B 必须进行强制类型转换(B = (B)A)
implicit 表示隐式转换,如从 B -> A 只需直接赋值(A = B)
隐式转换可以让我们的代码看上去更漂亮、更简洁易懂,所以最好多使用 implicit 运算符。不过!如果对象本身在转换时会损失一些信息(如精度),那么我们只能使用 explicit 运算符,以便在编译期就能警告客户调用端。

其次,operator 关键字用于在类或结构声明中声明运算符。

经典用法:

struct Currency
{
public uint Dollors;
public ushort Cents;
public Currency(uint dollors, ushort cents)
{
this.Dollors = dollors;
this.Cents = cents;
}
public override string ToString()
{
return string.Format("${0}.{1,-2:00}", Dollors, Cents) ;
}
public static string GetCurrencyUnit()
{
return "Dollars";
}
public static explicit operator Currency(float value)
{
checked
{
uint dollars=(uint)value;
ushort cents = (ushort)((value - dollars) * 100);
return new Currency(dollars,cents);
}
}
public static implicit operator float (Currency value)
{
return value.Dollors+(value.Cents/100.0f);
}
public static implicit operator Currency(uint value)
{
return new Currency(value,0);
}
public static implicit operator uint(Currency value)
{
return value.Dollors;
}
}

其他参考文档:http://www.cnblogs.com/hunts/archive/2007/01/17/operator_explicit_implicit.html


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接

Powered By Z-BlogPHP 1.7.3

Copyright www.skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864