北大青鸟鲁广校区

北大青鸟鲁广校区

  • 北大青鸟徐东校区
  • 北大青鸟光谷校区
  • 北大青鸟宏鹏IT校区
  • 荆州青鸟之家
  • 襄阳青鸟之家

15902769092

百日千才

.NET中的静态与非静态 北大青鸟.net培训课程

2013-03-28 12:14来源:武汉北大青鸟鲁广校区作者:武汉宏鹏

      北大青鸟武汉宏鹏鲁广校区.net培训课程之.net中的静态与非静态。

静态类 vs 普通类

静态类与普通类的区别有以下几点:

1)静态类无法实例化而普通类可以;

2)静态类只能从System.Object基类继承;普通可以继承其它任何非static和非sealed类,但也只能继承一个类;

3)静态类不能继承接口;普通类可以继承多个接口;

4)静态类只能包含静态成员;普通类可以包含静态和非静态成员;

5)静态类不能作为字段,方法参数和局部变量使用;普通类可以;

静态类的意义:

可以用静态类封装一组不与任何对象相关联的方法,如Math类,Console类。

静态构造函数 vs 实例构造函数

静态构造函数与实例构造函数的区别有以下几点:

1)静态构造函数属于类,在次用到该类时执行且只执行一次;实例构造函数属于对象,在每次初始化一个新对象的时候都会执行;

2)静态构造函数只能定义一次,且不能包含参数;实例构造函数可以定义重载,且可以包含参数;

3)静态构造函数只能访问类型的静态字段;实例构造函数可以访问类型的静态和非静态字段;

4)静态类不能包含访问修饰符,默认为private.

静态构造函数的意义:

设置类型的初始化,例如初始化类型需要的实例对象,为类型的静态字段赋值等。

静态方法 vs 实例方法

静态方法与实例方法的区别有以下几点:

1)静态方法属于类,通过类来调用;实例方法属于对象,通过对象来调用;

2)静态方法不能访问类的非静态成员;

静态方法的意义:

完成一个与特定对象无关的功能。

静态字段 vs 非静态字段

静态字段与非静态字段的区别:

静态字段属于类,通过类来调用;非静态字段属于对象,通过对象来调用。

静态字段的意义:

可以用静态字段来记录一些属于类本身的信息。

代码演示

1 publicclass Test

2    {

3 publicint i = 10;

4 publicstaticint j = 20;

5 publicint k;

6  

7 public Test()

8        {

9             Console.WriteLine("i is a non-static field, its value is {0}", i);

10             Console.WriteLine("j is a static field, its value is {0}", j);

11        }

12

13public Test(int k)

14        {

15this.k = k;

16             Console.WriteLine("i is a non-static field, its value is {0}", i);

17             Console.WriteLine("j is a static field, its value is {0}", j);

18             Console.WriteLine("k is a non-static field, its value is {0}", k);

19        }

20

21static Test()

22        {

23             Console.WriteLine("I am a static constructor, I couldn't contain any parameters!");

24             Console.WriteLine("I couldn't access to the non-static field i, I can only access to the static field j, the value of j is {0}", j);

25        }

26

27publicvoid Print()

28        {

29             Console.WriteLine("I am a instance method, I can access both the non-static field and the static field!");

30             Console.WriteLine("The value of i is {0} and the value of j is {1}", i, j);

31        }

32

33publicstaticvoid StaticPrint()

34        {

35             Console.WriteLine("I am a static method, I couldnt access to the non-static field i,  I can only access to the static field j, the value of j is {0}", j);

36        }

37     }

1class Program

2    {

3staticvoid Main(string[] args)

4        {

5             Test t1 = new Test();

6             Test t2 = new Test(30);

7

8            Console.WriteLine(Test.j);

9            Console.WriteLine(t1.i);

10            Console.WriteLine(t2.k);

11

12            Test.StaticPrint();

13            t1.Print();

14            Console.Read();

15        }

16     }

运行结果

北大青鸟.net培训课程

 

 

关闭

只为了方便您就学 北大青鸟鲁广校区 北大青鸟鲁广校区

武汉市洪山区珞喻路724号(地铁二号线光谷广场站F口出)

全真项目实战 入学签就业协议

Copyright (c) 2006-2020 武汉宏鹏职业培训学校 版权所有 All Rights Reserved.