Skip to content

Instantly share code, notes, and snippets.

@yushiro
Last active December 17, 2015 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yushiro/5660175 to your computer and use it in GitHub Desktop.
Save yushiro/5660175 to your computer and use it in GitHub Desktop.

#C#静态构造函数

1.静态构造函数既没有访问修饰符,也没有参数。因为是.NET调用的,所以像public和private等修饰符就没有意义了。

2.是在创建第一个类实例或任何静态成员被引用时,.NET将自动调用静态构造函数来初始化类,也就是说我们无法直接调用静态构造函数,也就无法控制什么时候执行静态构造函数了。

3.一个类只能有一个静态构造函数。

4.无参数的构造函数可以与静态构造函数共存。尽管参数列表相同,但一个属于类,一个属于实例,所以不会冲突。

5.最多只运行一次。

6.静态构造函数不可以被继承。

7.如果没有写静态构造函数,而类中包含带有初始值设定的静态成员,那么编译器会自动生成默认的静态构造函数。

##创建某个类型的第一个实例时,所进行的操作顺序为: 1.静态变量设置为0

2.执行静态变量初始化器

3.执行基类的静态构造函数

4.执行静态构造函数

5.实例变量设置为0

6.执行衯变量初始化器

7.执行基类中合适的实例构造函数

8.执行实例构造函数

同样类型的第二个以及以后的实例将从第五步开始执行.

###私有构造器先于静态构造器执行(在静态构造器从未执行过的情况下)

public class ErrorMsg
    {
        private static readonly ErrorMsg _Instance = new ErrorMsg();

        public static ErrorMsg Instance
        {
            get { return ErrorMsg._Instance; }
        } 
        static ErrorMsg()
        {
            Console.WriteLine("this is static construct");
        }
        private ErrorMsg() 
        {
            Console.WriteLine("this is private construct");
            Console.WriteLine(_ErrMsgCache);
        }
        private static Dictionary<int, string> _ErrMsgCache = new Dictionary<int, string>();

        public string GetErrMsg(int errId)
        {
            if(_ErrMsgCache.ContainsKey(errId)) return _ErrMsgCache[errId];
            return "";
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment