日期:2014-05-17  浏览次数:20897 次

我自定义的Clone函数不能被调用,为什么?
我写了个小程序,可以执行:

    public class d : System.ICloneable
    {
    public class d : System.ICloneable
    {
        public d(int ii) : base()
        {
            i = ii;
            Console.WriteLine("ctor");
        }
        ~d() { Console.WriteLine("dtor"); }
        public Object Clone()
        {
            return new d(i);
        }
        public int i;
    }
    class Program
    {
        static void Main(string[] args)
        {
            d d1 = new d(12);
            d d2 = d1;
            d2.i = 13;
            Console.WriteLine(d1.i);
        }
    }

运行输出是:

d ctor
13
d dtor
Press any key to continue . . .

但是我期待的是,既然class d实现了Clonable接口,那么d d2=d1就是一个新的对象创建,那么应该调用Clone函数对吧? 但是我调试发现并没有进入Clone函数,d2仍然是对于d1的引用。

我的代码错在哪里? 应该怎么改呢?

------解决方案--------------------
要显式调用:d d2 = (d)d1.Clone();