静态构造函数的意义

废话不说,上Dome!

  /// <summary>
    /// 静态构造函数,模拟类
    /// </summary>
    public class MyStaticClass
    {
        public static readonly string myStaticString;
        public string myString;

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static MyStaticClass()
        {
            myStaticString = "静态构造函数初始化";
        }

        /// <summary>
        /// 实例构造函数
        /// </summary>
        public  MyStaticClass()
        {
            myString = "默认实例构造函数";
        }

        /// <summary>
        /// 实例构造函数
        /// </summary>
        /// <param name="param">传入参数</param>
        public  MyStaticClass(string param)
        {
            myString = param;
        }

    }

-------------------------------------------------------------------

     /// <summary>
        /// 调用静态构造函数
        /// </summary>
        private void BindInfo()
        {
            string strValue = string.Empty;

            MyStaticClass myObj_1 = new MyStaticClass();
            strValue = myObj_1.myString;

            MyStaticClass myObj_2 = new MyStaticClass("赋值的实例构造函数");
            strValue=myObj_2.myString;

            string strStatic= MyStaticClass.myStaticString;
            
 
        }

总结:

  1. 一个类中只能有一个静态构造函数
  2. 静态构造函数不能有参数,返回值,访问标识符。
  3. 静态函数只在加载类的时候执行一次,而实例构造函数,在类实例化时,都会执行。
  4. 一个类中,静态构造函数和无参构造函数,可以同时存在。因为加载类是调用静态构造函数;实例化类时,调用实例构造函数。
  5. 静态构造函数的调用要早于实例构造函数。
  6. 静态构造函数,仅执行一次。s
posted on 2011-06-23 18:10  Spider-Man  阅读(129)  评论(0)    收藏  举报