本文是小编为大家收集整理的关于何时调用静态构造函数?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
什么时候调用静态构造函数?请举例说明.谢谢.
推荐答案
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx[^] 是一个很好的资源,您可以在其中找到一些此类问题的答案.
拿起一本书对你也有帮助.
在应用程序域的生命周期中第一次使用该类之前,每个类只调用一次静态构造函数.这个"使用的"包括一切:创建类的实例(当然,如果类本身是非静态的,这是可能的),调用任何类的方法或属性(必须是静态的)导致静态构造,仅仅是因为任何实例方法的调用总是会进行某些实例的创建,这将导致静态构造函数的调用更快),访问(读取或写入)任何类的字段或属性,在类的某个事件实例的调用列表中添加一个处理程序……(我是不是忘了什么?希望不是:-)).
您真的不需要任何代码示例.只需向任何类添加一个静态构造函数,在它的第一个语句上放置一个断点,看看会发生什么.—SA
静态构造函数用于初始化任何静态数据,或执行只需要执行一次的特定操作.在创建第一个实例或引用任何静态成员之前自动调用它
问题描述
When the static constructor would be called? Please do explain with example. Thanks.
推荐答案
http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx[^] is a good resource where you can find answers to some such questions.
Picking up a book could help you too.
The static constructor is called only once per class right before the class is used for the very first time in the life time of the application domain. This "used" includes everything: creation of the instance of the class (which is possible if the class itself is non-static, of course), a call of any of the class''s methods or properties (which have to be static to cause static construction, simply because calling of any instance method will always be proceeded be creation of some instance, which will cause the call of the static constructor sooner), access (read or write) of any class''s fields or properties, adding a handler to the invocation list of some event instance of the class… (did I forget anything? hope not :-)).
You don''t really need any code samples. Just add a static constructor to any class, put a breakpoint on it''s fist statement and see what happens.
—SA
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced
相关标签/搜索