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


本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

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

会员中心
搜索
«    2024年4月    »
1234567
891011121314
15161718192021
22232425262728
2930
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864