【问题标题】:Refactoring MemberwiseClone to use a constructor重构 MemberwiseClone 以使用构造函数
【发布时间】:2016-09-23 01:04:41
【问题描述】:

我尝试将copy 方法重构为copy2,如下所示:

class A
{
    public readonly int x = 42;
    public int y;
    public A(int y)
    {
        this.y = y;
    }
    public A copy(int y)
    {
        var c = (A)MemberwiseClone();
        c.y = y;
        return c;
    }
    public A copy2(int y)
    {
        return new A(y);
    }
}

(因为此代码的真实版本确实覆盖了MemberwiseClone 之后的大约一半字段)并且旨在使y 只读。这对As 很有效。但我们也有:

class B : A
{
    public B(int y) : base(y)
    {
    }
}

并且MemberwiseClone 正确地保留了它正在复制的东西的类型,但是我的copy2 每次都会创建一个新的A。假设B 否则实际上仍然只是A 的别名,那么创建正确类型的最佳方法是什么?

【问题讨论】:

    标签: c# clone


    【解决方案1】:

    我目前的实际答案是保留代码与 MemberwiseClone 保持原样,然后破坏复制的一半,但到目前为止我提出的解决方案使 copy virtualoverride 它在B:

    class A
    {
        public readonly int x = 42;
        public readonly int y;
        public A(int y)
        {
            this.y = y;
        }
        public virtual A copy(int y)
        {
            return new A(y);
        }
    }
    class B : A
    {
        public B(int y) : base(y)
        {
        }
        public override A copy(int y)
        {
            return new B(y);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多