有一个多月没有自己写过类什么的了,一直都在用NBear的gateways在那里做些表面功夫。今天开始写我的新项目 BabyStreet 的代码,写了一个数据提供类,没什么实际的意义的类,就是获得那个static的 Linq to sql 的 DataContent,我居然写出了下面的代码:
public static class DataProvider
{
public static BabyStreetSqlData db;
private static object _lock = new object();
public DataProvider()
{
if (db == null)
{
lock (_lock)
{
// Do this again to make sure db is still null
if (db == null)
{
db = new BabyStreetSqlData();
}
}
}
}
}
这个有明显的错误了,在一个static的类里面写上一个构造函数,有点意思啊。还有居然忘记了如果这样创建一个对象
BabyStreetSqlData cb=DataProvider.db;
后这个对象是copy了DataProvider.db还是直接引用到DataProvider.db。写个函数测试一下:
public class Baby
{
public string Name { get; set; }
public string Age { get; set; }
public Baby(string name, string age)
{
this.Name = name;
this.Age = age;
}
}
public static class BabyProvider
{
public static Baby Jesse = new Baby("jesse","23");
}
class Program
{
static void Main(string[] args)
{
Baby Kucao = BabyProvider.Jesse;
Console.WriteLine ("BabyProvider.Jesse Information:");
Console.WriteLine(BabyProvider.Jesse.Name );
Console.WriteLine("Kucao Information:");
Console.WriteLine(Kucao.Name);
Kucao.Name = "Kucao";
Console.WriteLine("=========================================");
Console.WriteLine("BabyProvider.Jesse Information:");
Console.WriteLine(BabyProvider.Jesse.Name);
Console.WriteLine("Kucao Information:");
Console.WriteLine(Kucao.Name);
Console.ReadLine();
}
}
运行后的结果为:
BabyProvider.Jesse Information:
jesse
Kucao Information:
jesse
=========================================
BabyProvider.Jesse Information:
Kucao
Kucao Information:
Kucao
看来是引用的。好多的都忘记了,郁闷啊,恶补吧。