The Programming Language Tips[2]

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 chelsea 的 blog

 


静态构造函数

问题

1,在工具类中,通常有一些初始化需要在任何静态方法被调用前进行,如配置信息的读取

2,普通类中的复杂的静态信息,需要在任何实例方法被调用前初始化

我见过的解决方法

1,在每个静态方法中都调用必需的初始化步骤

     public class someutilclass {

         private someutilclass(){

         } 

         private static void init(){

              //....

         } 

         public static string getuid(){

              init();

              return uid;

         }

          public static string getconnectionstring(){

              init();

              return connstring;

         }

     }

2,在普通构造函数中初始化

     public class somemapperclass{

         private static hashtable types;

         public somemapperclass(){

              if(types == null){

                   types = new hashtable();

                   types.add("red", color.red);

                   types.add("green", color.green);

                   types.add("blue", color.blue);

              }

         } 

         public color getcolor(string color){

              return (color)types[color];

         }

     }

 

本文关键:The Programming Language Tips
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top