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

来源:互联网 发布:数据堂众包 编辑:程序博客网 时间:2024/05/16 16:54

这个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

0 0
原创粉丝点击