0

I have a DAL base class ( data access ) which has 2 members:

/*1*/    class BaseDal
/*2*/       {
/*3*/           static DatabaseProviderFactory factory = new DatabaseProviderFactory();
/*4*/           static SqlDatabase sqlServerDB = factory.Create("ExampleDatabase") as SqlDatabase;
/*5*/       }
/*6*/   
/*7*/   
/*8*/   subclasses : 
/*9*/   
/*10*/    class MyCustomerDal:BaseDal
/*11*/       {
/*12*/          ...
/*13*/          ...
/*14*/          public static DataTable GetData()
/*15*/            {
/*16*/             // do something....
/*17*/            }
/*18*/   
/*19*/       }
/*20*/   

My question is about lines 3,4.

please notice that I don't create new MyCustomerDal cuz I dont need an instance but only to use the method GetData() (static).Also , those 2 lines can serve all derived classes.

And here is my question :

I want those 2 initializers (line 3,4) to be laze initialize.

well I have 2 options :

option 1

I can set a static ctor which basically means that those members will be running only when the class is accessed ( beforefieldinit issue).

option 2

I could use Lazy :(+property)

/*1*/   Lazy<SqlDatabase> myDb = new Lazy<SqlDatabase>(() => factory.Create("ExampleDatabase") as SqlDatabase);
/*2*/   
/*3*/           protected SqlDatabase Mydb 
/*4*/           {
/*5*/               get { return myDb.Value; }
/*6*/           }

But to tell you the truth I don't know which approach is better....

4

2 回答 2

1

我认为您应该使用static Lazy<T>字段(可以选择添加静态属性来访问惰性值,就像您一样)。

这样,您可以在不需要实例的情况下使用它们,并且还具有完全惰性的行为。

您的选项 1 将在您访问其中一个字段时立即初始化这两个字段,这可能是不可取的。

于 2013-07-12T21:55:49.407 回答
1

根据您的评论更新

我建议您阅读在 C# 中实现单例模式(Jon Skeet 撰写)和他的文章C# and beforefieldinit

在您的情况下,最好的方法似乎也是最明确的。使用惰性< T >。

你的第一种方法更糟糕。ECMA-335 第 6 版 / 2012 年 6 月(公共语言基础设施 (CLI) 分区 I 至 VI,第 43-44 页)

3:如果标记为 BeforeFieldInit,则该类型的初始化方法在或之前的某个时间执行,首先访问为该类型定义的任何静态字段。

4:如果未标记 BeforeFieldInit 则该类型的初始化方法在以下位置执行(即,由以下方式触发):

一个。首次访问该类型的任何静态字段,或

湾。首次调用该类型的任何静态方法,或

C。如果它是值类型,则首次调用该类型的任何实例或虚拟方法,或者

d。首次调用该类型的任何构造函数。

因此,如果类型标记为 BeforeFieldInit 或未标记为 BeforeFieldInit,则使用 Lazy< T > 比您的第一种方法更好。

于 2013-07-12T21:34:57.297 回答