“抽象类”字段中的继承类被神秘覆盖

时间:2018-07-07 19:56:38

标签: c#

我的问题是,一旦程序一次到达MyMethod(),它将LocalField和InheritedProperty设置为相同的一个指针,这意味着每当InheritedProperty更改LocalField时,它也会自动执行。

class Inherited : AbstractClass
{
    protected override void MyMethod()
    {
        LocalField = InheritedProperty;
    }

    public void MyNewMethod()
    {
        //Is the new Array different?
        //Do something
    }

    public long[] LocalField;

    protected override long[] InheritedProperty => RetrtieveNewArray;
}

是否可能有人将我的LocalField设置为独立于InheritedProperty的新字段?

1 个答案:

答案 0 :(得分:1)

您可以克隆数组:

LocalField = (long[]) InheritedProperty.Clone();

这将创建原始数组的独立副本。

在您的情况下,数组元素类型是值类型(long),这意味着克隆将复制所有数字。但是,如果对包含引用的数组执行相同的操作,则只会得到“浅”副本,这意味着克隆数组中的引用将引用与原始数组中的引用相同的对象。这与问题代码无关,但通常在克隆数组时应该注意。