Effective C#之13: Initialize Static Class Members with Static Constructors

rel="File-List" href="file:///C:%5CDOCUME%7E1%5CHelios%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_filelist.xml"> rel="themeData" href="file:///C:%5CDOCUME%7E1%5CHelios%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_themedata.thmx"> rel="colorSchemeMapping" href="file:///C:%5CDOCUME%7E1%5CHelios%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_colorschememapping.xml">

Item 13: Initialize Static Class Members with Static Constructors

用静态构造函数初始化静态类成员

You know that you should initialize static member variables in a type before you create any instances of that type. C# lets you use static initializers and a static constructor for this purpose. A static constructor is a special function that executes before any other methods, variables, or properties defined in that class are accessed. You use this function to initialize static variables, enforce the singleton pattern, or perform any other necessary work before a class is usable. You should not use your instance constructors, some special private function, or any other idiom to initialize static variables.

在创建一个类型的任何实例之前,应该初始化其中的静态成员变量。C#允许使用静态初始化器和静态构造函数来达到目的。静态构造函数是一个特殊的方法,它在类中任何其它方法、变量或者属性被访问之前被执行。在一个类被使用前,用该方法初始化静态变量,强制单件模式,或者执行任何其它必要的工作。不应该使用实例构造函数、一些特殊的私有方法、任何其它习惯来初始化静态变量。

As with instance initialization, you can use the initializer syntax as an alternative to the static constructor. If you simply need to allocate a static member, use the initializer syntax. When you have more complicated logic to initialize static member variables, create a static constructor.

和实例初始化一样,可以使用初始化器语法作为静态构造函数的变体。如果你需要简单的分配一个静态成员,那么可以使用初始化器语法。当你有更复杂的逻辑来初始化静态成员变量时,请创建静态构造函数。

Implementing the singleton pattern in C# is the most frequent use of a static constructor. Make your instance constructor private, and add an initializer:

C#里面实现单件模式,是对静态构造函数最频繁的使用。

  1.     public class MySingleton
  2.     {
  3.         private static readonly MySingleton theOneAndOnly = new MySingleton();
  4.         public static MySingleton TheOnly
  5.         {
  6.             get
  7.             {
  8.                 return theOneAndOnly;
  9.             }
  10.         }
  11.         private MySingleton()
  12.         {
  13.         }
  14.         // remainder elided
  15.      }

The singleton pattern can just as easily be written this way,in case you have more complicated logic to initialize the singleton:

单件模式可以像这样就这么简单的写出来。万一,你有更复杂的逻辑要初始化该单件:

  1.     public class MySingleton
  2.     {
  3.        private static readonly MySingleton theOneAndOnly;
  4.         static MySingleton()
  5.         {
  6.             TheOneAndOnly = new MySingleton();
  7.         }
  8.         public static MySingleton TheOnly
  9.         {
  10.             get
  11.             {
  12.                 return _theOneAndOnly;
  13.             }
  14.         }
  15.         private MySingleton()
  16.         {
  17.         }
  18.         // remainder elided
  19.     }

As with instance initializers, the static initializers are called before any static constructors are called. And, yes, your static initializers execute before the base class's static constructor.

和实例初始化器一样,静态初始化器在任何静态构造函数被调用之前被调用。同时,静态初始化器在基类的静态构造函数之前被执行。当你的类型首次被加载到应用程序空间时,

The CLR calls your static constructor automatically when your type is first loaded into an application space. You can define only one static constructor, and it must not take any arguments. Because static constructors are called by the CLR, you must be careful about exceptions generated in them. If you let an exception escape a static constructor, the CLR will terminate your program. Exceptions are the most common reason to use the static constructor instead of static initializers. If you use static initializers, you cannot catch the exceptions yourself. With a static constructor, you can (see Item 45):

CLR自动调用静态构造函数。你可以仅仅定义一个静态构造函数,它必须不带任何参数。因为静态构造函数是由CLR调用的,你必须当心在它们中出现的异常。如果让异常跳出静态构造函数,CLR将会终止你的程序。使用静态构造函数而不是静态初始化器的最常见的原因就是异常处理。如果使用静态初始化器,就不可能自己捕获异常了。有了静态构造函数,才可以。( Item 45)

  1.         static MySingleton()
  2.         {
  3.             try
  4.             {
  5.                 theOneAndOnly = new MySingleton();
  6.             }
  7.             catch
  8.             {
  9.                 // Attempt recovery here.
  10.             }
  11.         }

Static initializers and static constructors provide the cleanest, clearest way to initialize static members of your class. They are easy to read and easy to get correct. They were added to the language to specifically address the difficulties involved with initializing static members in other languages.

静态初始化器和静态构造函数提供了最洁净的、最直接的方式来初始化类的静态成员。它们容易阅读,容易写对。它们被加入到语言中来,对在其它语言中涉及到的和初始化静态成员相关的困难,进行了特殊的描述。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值