C# Explicit 和 Implicit

    Implicit 关键字告诉编译器只有为了生成代码来调用方法,不需要在源代码中显示调用类型转换方法;

    Explicit 只有在显示转换时,才会调用方法;

  1. public sealed class Rational  
  2. {  
  3.     public Rational(Int32 num)  
  4.     {  
  5.     
  6.     }  
  7.     //Rational转成Int32  
  8.     public Int32 ToInt32()  
  9.     {  
  10.         return   
  11.     }  
  12.     //隐式调用  
  13.     public static implicit operator Rational(Int32 num)  
  14.     {  
  15.         return new Rational(num);  
  16.     }  
  17.     //显示调用  
  18.     public static explicit operator Int32(Rational r)  
  19.     {  
  20.         return r.ToInt32();  
  21.     }  
  22. }  

调用例子:

  1. public sealed class Program  
  2. {  
  3.     public static void Main()  
  4.     {  
  5.         Rational r = 5;  
  6.         Int32 x = (Int32)r; //显示调用  
  7.     }  
  8. }  
posted @ 2019-05-05 21:27  MyPinky  阅读(166)  评论(0编辑  收藏  举报