Item 13:Initialize Static Class Members with Static Constructors

此博客为转载内容,转载自https://www.cnblogs.com/Grisson/archive/2005/08/12/213635.html ,涉及C#相关知识。
  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:
None.gif public   class  MySingleton
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
private static readonly MyClass theInit = new MyClass();
InBlock.gif  
private static readonly MyClass theCons;
InBlock.gif
InBlock.gif  
public static MyClass Init
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
get
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
return theInit;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
set
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      theInit 
= value;
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public static MyClass Cons
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
get
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
return theCons;
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
static MySingleton()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    theCons 
= new MyClass();
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  MySinleton()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockEnd.gif  }

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

转载于:https://www.cnblogs.com/Grisson/archive/2005/08/12/213635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值