在设计类时,是否有关于初始化类字段的指导方针?有两种不同的初始化方法。我可以使用内联字段初始化程序,也可以在构造函数中初始化它们。它变得更加...有趣,当引入静态字段时,可以在定义时,在静态构造函数中或在实例构造函数中初始化字段,并检查该字段是否已设置。当引入工厂时,这变得更加混乱。
示例 1 - 内联初始化
public class ExampleOne
{
private readonly IDictionary _collection = new Dictionary();
...
}
示例 2 - 构造函数初始化
public class ExampleTwo
{
private readonly IDictionary _collection;
public ExampleTwo()
{
_collection = new Dictionary();
}
...
}
示例 3 - 静态内联初始化
public class ExampleThree
{
private static readonly IDictionary __collection = new Dictionary();
...
}
示例 4 - 静态构造函数初始化
public class ExampleFour
{
private static IDictionary __collection;
static ExampleFour()
{
_collection = new Dictionary();
}
...
}
示例 5 - 静态/实例构造函数混合初始化
public class ExampleFive
{
private static readonly IDictionary __collection;
private static IDictionary __anotherCollection;
static ExampleFive()
{
_collection = new Dictionary();
}
public ExampleFive()
{
if( __anotherCollection == null )
{
__anotherCollection = new Dictionary();
}
}
...
}
示例 6 - 工厂方法
public class ExampleSix
{
private static readonly IDictionary __collection;
private static IDictionary __anotherCollection;
static ExampleSix()
{
_collection = new Dictionary();
}
public static ExampleSix Create()
{
if( __anotherCollection == null )
{
__anotherCollection = new Dictionary();
}
var example = new ExampleSix();
return example;
}
...
}
目前,我所拥有的课程倾向于混合所有这些。尽管我试图避免在实例构造函数中设置静态字段。
示例 7 - 混合
public class ExampleSeven
{
private static readonly IDictionary __collection = new Dictionary();
private static readonly IDictionary __anotherCollection;
private static readonly IDictionary __thirdCollection;
private static IDictionary __fourthCollection;
static ExampleSeven()
{
__anotherCollection = new Dictionary();
}
public ExampleSeven()
{
if( __thirdCollection == null )
{
__thirdCollection = new Dictionary();
}
}
public static ExampleSeven Create()
{
if( __fourthCollection == null )
{
__fourthCollection = new Dictionary();
}
var example = new ExampleSeven();
return example;
}
...
}
我更关心的是,从示例中可以看出,字段是类对象而不是简单的原语。我知道在声明字段时初始化字段会将类标记为beforeinit
,并且我无法传递this
到声明时初始化的字段中。我关心的主要是与上述七个例子类似的情况。通过这种方式混合它们,我是否会为任何不可预见的问题做好准备?