开发者

Difference between Initializer or Static Initiliazer?

开发者 https://www.devze.com 2022-12-09 15:49 出处:网络
When I was working with XmlDOM in Asp.Net, there was a pattern like this : `XmlReader reader = XmlReader.Create()\".

When I was working with XmlDOM in Asp.Net, there was a pattern like this : `XmlReader reader = XmlReader.Create()".

And then I encountered the same pattern several times later.

I like to know what's the difference between Static Constructor and "new ClassName()" Constructor (I am not sure if I am using right terms to describe what I mean).

I am not asking what 开发者_如何学JAVAXmlReader.Create() does, what I want to learn is why I would use static constructor over than ? What kind of aspect would it provide ? What are the things I can do with static constructor but I can't do with new keyword constructor.

Thanks in advance.


First of all, let's get terminology in order. XmlReader.Create is not a static constructor. It's just a static method that (typically) returns new instances of objects; this is normally called "factory method". A "static constructor" would be a constructor declared with keyword static, used to initialize static members of the class:

class MyClass {
   static MyClass() { ... } // static constructor
}

Now as to why a factory method may be preferable. There can be several reasons.

For one, a constructor (invoked via new) always has to either provide a newly instantiated object, or throw an exception. A factory method can return null if that makes sense, or it may maintain some cache of objects, and avoid creating a new one all the time (e.g. when objects are immutable).

Another reason is that when you do new T(), you always get specifically an instance of T. A factory method could instead create an instance of some subclass of T, depending on input parameters and other factors. In case of XmlReader, this is precisely what happens - XmlReader itself is abstract, so there cannot be any instances of it; however, there are several subclasses that serve different purposes (validating/non-validating, stream backend / DOM backed, etc), and XmlReader.Create picks the right one based on overload and arguments you supply to it.


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.Classic constructor is used to initialize instance variables, and called every time the object is created


You can do the same in both constructors. THere is no difference. However, the static constructor is only called ONCE in the lifetime of your program and is only allowed for classes with static members. It can initialize the private static variables before using them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号