Note: What you have is not a static constructor, it's a static function that creates the instance rather than calling the instance constructor yourself. A static constructor is a different thing entirely.
The factory pattern is a classic example of using a function (static or not) to instantiate a type rather than using the constructor directly. Note that the actual instance constructor will get called no matter what, but the static function provides a layer of indirection that allows it to return an instance of any type that either is or inherits from the return type, rather than only instances that are the return type.
For example:
public abstract class BaseClass
{
public static BaseClass Create(int parameter)
{
if (parameter == 1)
{
return new Class1();
}
else
{
return new Class2();
}
}
}
internal class Class1 : BaseClass
{
//code here ...
}
internal class Class2 : BaseClass
{
//code here ...
}
This allows you to hide Class1
and Class2
from external assemblies while still allowing the consumer to deal with something specialized.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…