有一个多月没有自己写过类什么的了,一直都在用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

看来是引用的。好多的都忘记了,郁闷啊,恶补吧。

相关文章:

  • 2021-05-13
  • 2021-10-30
  • 2021-08-19
  • 2021-06-28
  • 2021-08-29
  • 2021-11-20
  • 2022-01-19
  • 2021-10-10
猜你喜欢
  • 2021-08-28
  • 2021-05-24
  • 2021-09-28
  • 2021-06-23
  • 2021-11-16
  • 2022-01-12
  • 2021-07-09
相关资源
相似解决方案