[对象和类型]9.静态构造函数

Posted on 2009-09-26 12:46  Relax Active  阅读(142)  评论(0)    收藏  举报

说明:

静态构造函数具有以下特点:

  • 静态构造函数既没有访问修饰符,也没有参数。
  • 在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化
  • 无法直接调用静态构造函数。
  • 在程序中,用户无法控制何时执行静态构造函数。
  • 静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。
  • 静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。
  • 如果静态构造函数引发异常,运行时将不会再次调用该构造函数,并且在程序运行所在的应用程序域的生存期内,类型将保持未初始化。

 

代码示例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing;

 

namespace Demo6

{

    class UserPreferences

    {

        public static readonly Color BackColor;   //声明类的静态成员

        static UserPreferences()   //构造静态函数

        {

            DateTime now = DateTime.Now;

            if(now.DayOfWeek == DayOfWeek.Saturday

                || now.DayOfWeek == DayOfWeek.Sunday)

            BackColor = Color.Green;

            else

            BackColor = Color.Red;

        }

        private UserPreferences() 

        {

        }

    }

}

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing;

namespace Demo6

{

    class Pro

    {

        static void Main(string[] args)

        {

            Console.WriteLine("UserPreferences:BackColor is:

" + UserPreferences.BackColor.ToString());

        }

    }

}

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3