Implicit 关键字告诉编译器只有为了生成代码来调用方法,不需要在源代码中显示调用类型转换方法;
Explicit 只有在显示转换时,才会调用方法;
- public sealed class Rational
- {
- public Rational(Int32 num)
- {
- }
- //将Rational转成Int32
- public Int32 ToInt32()
- {
- return
- }
- //隐式调用
- public static implicit operator Rational(Int32 num)
- {
- return new Rational(num);
- }
- //显示调用
- public static explicit operator Int32(Rational r)
- {
- return r.ToInt32();
- }
- }
调用例子:
- public sealed class Program
- {
- public static void Main()
- {
- Rational r = 5;
- Int32 x = (Int32)r; //显示调用
- }
- }