首页 > 其他 > 详细

C#关键字,explicit和implicit

时间:2014-02-26 14:05:14      阅读:360      评论:0      收藏:0      [点我收藏+]

这两个关键字可以在自己的类中,类型间转换时显式的还是隐式的

如下例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static implicit operator float(Currency value)
{
    return value.dollars + (value.cents / 100.0f);
}
 
public static explicit operator Currency(float value)
{
    checked
    {
        uint dollars = (uint)value;
        ushort cents = Convert.ToUInt16((value - dollars) * 100);
        return new Currency(dollars, cents);
    }
}
public static implicit operator float(Currency value)
表示Currency到float是隐式转换,如:
Currency a;
float b = a;

public static explicit operator Currency(float value)
表示float到Currency需要强制转换,如:
float a;
Currency b = (Currency)a;

C#关键字,explicit和implicit

原文:http://www.cnblogs.com/malc1988/p/3567687.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!