码迷,mamicode.com
首页 > Windows程序 > 详细

C#学习笔记(一):一些知识点的记录

时间:2015-05-09 13:20:47      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

类与结构体的区别:

  • 定义类使用class,定义结构体使用struct。
  • 结构体不能对字段进行初始化,类可以。
  • 如果没有为类定义构造函数,则C#会自动定义一个无参的构造函数,如果定义了构造函数则不会自动定义无参的构造函数。而结构体无论是否定义构造函数都会自动添加一个无参的构造函数。
  • 结构体不能定义一个无参的构造函数,可以定义有参数的构造函数。类则无此限制。
  • 在结构体的有参构造函数中,必须为所有的字段进行赋值。
  • 创建结构体不使用new。
  • 结构体不能继承结构体或类但可以实现接口,类不能继承结构体。
  • 类是引用类型,结构体是值类型。
  • 结构体不能定义析构函数,类可以。
  • 结构体不能使用abstract和sealed关键字,类可以。

 

指定枚举的类型:

默认情况下枚举的类型为int类型,但是我们也可以指定枚举类型,如下:

1 enum Gender : byte
2 {
3     Female,
4     Male
5 }

 

静态构造函数:

C#中还存在静态构造函数,即创建动态实例或者引用静态属性之前,都会调用静态构造函数。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace StudyTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine(StaticConstructor.name);
14             Console.WriteLine(StaticConstructor.name);
15             Console.ReadKey();
16         }
17     }
18     
19     class StaticConstructor
20     {
21         private static string _name;
22 
23         static StaticConstructor()
24         {
25             Console.WriteLine("静态构造函数被调用了!");
26             _name = "StaticConstructorInstance";
27         }
28 
29         public static string name
30         {
31             get { return _name; }
32         }
33     }
34 }

输出如下:

1 静态构造函数被调用了!
2 StaticConstructorInstance
3 StaticConstructorInstance

 

析构函数:

当对象被GC回收时会调用析构函数,一般情况无需显示定义析构函数,但是当需要销毁非托管资源时可以显示定义析构函数进行处理。析构函数的显示定义如下:

1 class Person
2 {
3     ~Person()
4     {
5         Console.WriteLine("析构函数被调用了!");
6     }
7 }

使用析构函数时需要注意下面几点:

  • 不能再结构体中使用;
  • 一个类只能有一个析构函数;
  • 无法继承或重载析构函数;
  • 不能显示调用,析构函数由垃圾回收器自动调用;
  • 析构函数没有修饰符也没有参数;

 

索引器:

当一个类需要使用类似数组的[]访问内部数据时可以使用索引器。索引器类似于属性,可使用get/set访问器,具体形式如下:

1 [修饰符] 数据类型 this[索引类型 index]
2 {
3     get { //返回数据 }
4     set { //设置数据 }
5 }

下面我们看一个例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace StudyTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             IndexTest it = new IndexTest();
14             it[0] = 1;
15             it[1] = 2;
16             it[2] = 3;
17 
18             Console.WriteLine(it[0]);
19             Console.WriteLine(it[1]);
20             Console.WriteLine(it[2]);
21             Console.ReadKey();
22         }
23     }
24     
25     class IndexTest
26     {
27         private int[] arr = new int[10];
28 
29         public int this[int index]
30         {
31             get { return arr[index]; }
32             set { arr[index] = value; }
33         }
34     }
35 }

输入如下:

1 1
2 2
3 3

 

C#学习笔记(一):一些知识点的记录

标签:

原文地址:http://www.cnblogs.com/hammerc/p/4486515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!