现在的位置: 首页 > 综合 > 正文

这两天发现的C#bug

2012年10月24日 ⁄ 综合 ⁄ 共 896字 ⁄ 字号 评论关闭

一个是Hashtable,如果在调用Add方法加入时用uint作为主键,取的使用用int,就不能取出放入的内容.我觉得这两种类型在进行hash处理时应该没有区别才对

一个是匿名委托,我觉得传递局部变量时有问题,对于值类型,传递的不是该值的一个拷贝,该值的变化居然会反映到委托调用时.下面是测试代码

   delegate void Print();

   class Program

   {

      static void Main(string[] args)

      {

        probDelegate();

      }

 

      static void probHashtable()

      {

        Hashtable t = new Hashtable();

        t.Add((uint)1, "hello");

        object o = t[1];

        object o2 = t[1U];

        //o will get nothing

        //o2 will get the problem value

        Console.WriteLine("o={0} o2={1}",o,o2);

      }

 

      static void probDelegate()

      {

        int[] b=new int[]{1,2,3};

        Print[] ps= new Print[2];

        for (int i = 0; i < 2; i++)

        {//构造委托时i的值是0,1

        //但在委托调用时却使用的是b[2]

           ps[i] = delegate{ doPrint(b[i]);};

        }

 

        for (int i = 0; i < ps.Length; i++)

        {

           ps[i]();

        }

        //the result is 3 3. NOT 1 2

      }

 

      static void doPrint(int d)

      {

        Console.WriteLine(d);

      }

   }

 

抱歉!评论已关闭.