正文

探讨一下静态构造函数(二)(C#版)2007-10-14 23:10:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/goalbell/30114.html

分享到:

因为前面的一篇的文章已介绍了静态构造函数的一些特性,这篇文章着重介绍静态构造函数的一些用法:

代码如下:

//代码段一

using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
  x = 100;
  y = 200;
}

 static void Main()
{
  Console.WriteLine("{0},{1}",MyClass.x,MyClass.y);//在C#中静态成员属于类的成员,不//需要实例化对象来调用。
 }

}

运行结果:100,200


//代码段二

class Test
    {
        private static int id = 5;
        public static int Id
        {
            get
            {
                return id;
            }
        }
      
    }
    class Test1
    {
        private static int id;
        static Test1()
        {
            if (Test.Id < 10)
            {
                id = 20;
            }
            else
            {
                id = 10;
            }
            Console.WriteLine("Static Constructor for Class Test1 called.");
        }
        public static void print()
        {
            Console.WriteLine("Test1.id=" + Test1.id);
        }
        static void Main(string[] args)
        {
            Test1.print();
        }
   
    }

运行结果:

Static Constructor for Class Test1 Called.
Test1.id = 20

结论:代码段二,在类Test1中静态成员不是一开始就初始化,而是在静态构造函数根据有条件地进行初始化。

阅读(2658) | 评论(4)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册