C#基础(三)
1)析构函数示例代码:
View Code
1 using System;
2 public class MyResource : IDisposable
3 {
4 private bool disposed = false;
5 public void Dispose()
6 {
7 Dispose(true);
8 }
9 public void close()
10 {
11 Dispose(true);
12 }
13 ~MyResource()
14 {
15 Dispose(false);
16 }
17 private void Dispose(bool disposing)
18 {
19 if(!this.disposed)
20 {
21 if(disposing)
22 {
23 Console.WriteLine("diaoyongyingyong Dispose()");
24 }
25 Console.WriteLine("shifang feituoguanziyuan");
26 disposed=true;
27 if(disposing)
28 {
29 GC.SuppressFinalize(this);
30 }
31 }
32 }
33 }
34
35 public class Test
36 {
37 static void Main()
38 {
39 MyResource mr = new MyResource();
40 try
41 {
42 Console.WriteLine("diaoyong mr");
43 }
44 finally
45 {
46 mr.Dispose();
47 }
48 Console.ReadLine();
49 }
50 }
2)简单的析构函数:
View Code
1 using System;
2 class A
3 {
4 public A()
5 {
6 Console.WriteLine("new A");
7 }
8 ~A()
9 {
10 Console.WriteLine("release A");
11 }
12
13 class Test
14 {
15 static void Main()
16 {
17 for (string s = ""; s != "end"; s = Console.ReadLine())
18 {
19 new A();
20 for (int i = 0; i < 50; i++)
21 {
22 byte[] b = new byte[1000];
23 }
24 }
25 }
26 }
27 }
3)简单的构造函数:
View Code
1 using System;
2 class A
3 {
4 public int i;
5 public string s;
6 public A()
7 {
8 }
9 public A(int i)
10 {
11 this.i = i;
12 }
13 public A(string s)
14 {
15 this.s = s;
16 }
17 public A(int i, string s)
18 {
19 this.i = i;
20 this.s = s;
21 }
22 class Test
23 {
24 static void Main()
25 {
26 A a = new A();
27 Console.WriteLine("the first gouzaoqi");
28 Console.WriteLine(a.i);
29 Console.WriteLine(a.s);
30
31 A a1 = new A(1);
32 Console.WriteLine("the second gouzaoqi");
33 Console.WriteLine(a1.i);
34 Console.WriteLine(a1.s);
35
36 A a2 = new A("I'm the third");
37 Console.WriteLine("the third gouzaoqi");
38 Console.WriteLine(a2.i);
39 Console.WriteLine(a2.s);
40
41 A a3 = new A(3, "I'm the fourth");
42 Console.WriteLine("the fourth gouzaoqi");
43 Console.WriteLine(a3.i);
44 Console.WriteLine(a3.s);
45 Console.ReadLine();
46 }
47 }
48 }
4)继承有关的构造函数:
View Code
1 using System;
2 class A
3 {
4 public A()
5 {
6 Console.WriteLine("wucan A");
7 }
8 public A(int i)
9 {
10 Console.WriteLine("youcan A");
11 }
12 }
13 class B : A
14 {
15 public B()
16 {
17 Console.WriteLine("wucan B");
18 }
19 public B(int i)
20 : base(i)
21 {
22 Console.WriteLine("youcan B");
23 }
24 }
25 class Test
26 {
27 static void Main()
28 {
29 B b = new B(100);
30 Console.ReadLine();
31 }
32 }
5)类的修饰符:
6)类型转换示例代码:
View Code
1 using System;
2 class Fruit
3 {
4 }
5 class Apple:Fruit
6 {
7 public int i=1;
8 }
9 class Conversions
10 {
11 static void Main()
12 {
13 Fruit f=new Fruit();
14 Apple a=new Apple();
15 Console.WriteLine(f is Fruit);
16 Console.WriteLine(f is Apple);
17 Console.WriteLine(a is Fruit);
18 Console.WriteLine(a is Apple);
19 Console.ReadLine();
20 }
21 }
7)abstract用于修饰抽象类,被abstract修饰的类不能被实例化。
sealed用于修饰密封类,被sealed修饰的类不能被继承。