Grisson's .net

源码之前,了无秘密

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  You know you should initialize static member variables in a type before you create ant instatnces of that type.
  C# let you use static initializers and a static constructor for this purpose.
  A static constructor is a special function that executes before any other methods,variable,or properties defined in that class are accessed.
  As with instance initializers,the static initializers are called before any static constructors are called.
  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. Like this:
public class MySingleton
{
  
private static readonly MyClass theInit = new MyClass();
  
private static readonly MyClass theCons;

  
public static MyClass Init
  
{
    
get
    
{
      
return theInit;
    }

    
set
    
{
      theInit 
= value;
    }

  }


  
public static MyClass Cons
  
{
    
get
    
{
      
return theCons;
    }

  }


  
static MySingleton()
  
{
    theCons 
= new MyClass();
  }


  MySinleton()
  
{
  }

}
你可以static constructor中添加try...catch块添加异常处理
posted on 2005-08-12 19:15  海盗  阅读(392)  评论(2编辑  收藏  举报