C# explicit implicit关键字、checked关键字

来源:互联网 发布:企业工单管理系统源码 编辑:程序博客网 时间:2024/06/07 10:12

//代码及部分解释参考C#高级编程、msdn


explicit关键字:

         声明必须通过转换来调用的用户定义的类型转换运算符。如果转换操作会导致异 常或丢失信息,则应将其标记为 explicit。 这可阻止编译器静默调用可能产生意外后果的转换操作。

implicit关键字:

         用于声明隐式的用户定义类型转换运算符。 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。隐式转换可以通过消除不必要的强制转换来提高源代码的可读性。 但是,因为隐式转换不需要程序员将一种类型显式强制转换为另一种类型,所以使用隐式转换时必须格外小心,以免出现意外结果。 一般情况下,隐式转换运算符应当从不引发异常并且从不丢失信息,以便可以在程序员不知晓的情况下安全使用它们。 如果转换运算符不能满足那些条件,则应将其标记为 explicit。

示例代码:

    class Program    {        private delegate string GetAString();        static void Main(string[] args)        {                       Currency balance = new Currency(40, 30);            uint value = balance;            uint testVal = 20;            float testExplicit = 50.8f;            //在调用implicit的时候,直接 = 转换即可,不用加强制转换符            Currency convertCurrency = testVal;            //在调用explicit的时候,需要加强制转换            Currency convertCurrencyTwo = (Currency)testExplicit;            Console.WriteLine("vlaue: {0}", value);            Console.WriteLine("convert implicit Currency: {0}", convertCurrency);            Console.WriteLine("convert explicit Currency: {0}", convertCurrencyTwo);            Console.ReadKey();        }    }    struct Currency    {        public uint Dollars;        public uint Cents;        public Currency(uint dollars, uint cents)        {            this.Dollars = dollars;            this.Cents = cents;        }        public override string ToString()        {            return string.Format("${0}.{1,2:00}", Dollars, Cents);        }        public static string GetCurrencyUnit()        {            return "Dollar";        }        /// <summary>        /// 显式的用户定义类型转换运算符        /// </summary>        /// <param name="value"></param>        /// <returns></returns>        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.Dollars + (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.Dollars;        }    }
运行结果:

checked关键字:

checked 和 unchecked关键字用来限定检查或者不检查数学运算溢出的;如果使用了checked发生数学运算溢出时会抛出OverflowException;如果使用了unchecked则不会检查溢出,算错了也不会报错。

checked unchecked关键字,参考下面博客:

http://www.cnblogs.com/yukaizhao/archive/2011/08/09/csharp-checked-unchecked-keywords.html

0 0
原创粉丝点击