1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
namespace 类型构造器 { class Program { static void Main( string [] args) { int a = 5; Single b=8; Rational rint = new Rational(a); Rational bsigle = new Rational(b); Rational r1 = 5; //int隐式转化为rational; Rational r2 = 3.14f; //single隐式转化为Rational Rational r3 = 4; Rational r4 = 6; Console.WriteLine(rint.GetType()); //输出为Rational Console.WriteLine(bsigle.GetType()); //输出为Rational Console.WriteLine(r3.ToInt32().GetType()); //输出为System.Int32 Console.WriteLine(r4.ToSingle().GetType()); //输出为System.Single Console.ReadKey(); } } } |
c#中implicit关键字告诉编译器为了生成代码来调用方法,不需要在源代码中进行显式转型,相反explicit告诉编译器只有在发现了显式转型时才调用方法。
implicit和explicit关键字之后指定operator关键字告诉编译器该方法时一个转换操作符。在operator之后,指定对象要装换成什么类型,圆括号里指定要从什么类型装换。