“new”关键字返回类的相同实例

问题描述 投票:0回答:1

我有这两个类,一个继承另一个类。

当外部脚本调用 .copy() 时,它始终接收父 DataComponent,而不是 BooleanProperty。

如果未调用 copy(),则会获得传递引用,从而导致对一个实例的更改影响另一个实例(因为它们是相同的;我不希望这样);

我相信这是一个我自己的问题,不知道语言的语法或其他东西,希望只是这样。

在 Windows 10 上使用 Unity 2020.3.17f1。

两个类的代码:

[System.Serializable]
public class DataComponent
{
    public DataComponent(string n = "")
    {
        name = n;
    }

    public string name;
    [System.NonSerialized]public string value;

    public DataComponent copy()
    {
        DataComponent ret = new DataComponent(this.name);
        ret.value = this.value;
        return ret;
    }
}

[System.Serializable]
public class BooleanProperty : DataComponent
{
    public BooleanProperty(string n = "") : base(n) { }

    public new bool value;

    public new BooleanProperty copy()
    {
        BooleanProperty ret = new BooleanProperty(name);
        ret.value = value;
        return ret;
    }
}

- 通过在 BooleanProperty 中声明一个单独的 copyBool() 方法解决了该问题。调用 copyBool() 按预期工作(返回一个 new 实例)

c# unity-game-engine inheritance instance pass-by-reference
1个回答
0
投票

这是因为您使用了

new
关键字来重写方法,而不是
override
。使用
new
关键字,您只需隐藏基本实现,当变量用作基本类型时,基本实现就会发挥作用。另外,
copy
方法应该是
virtual
中的
DataComponent

考虑这个简单的场景:

public class Base
{
    public virtual void Method()
    {
        Console.WriteLine("I am Base");
    }
}

public class Derived : Base 
{
    public override void Method()
    {
        Console.WriteLine("I am Dervied");
    }
}

public class DerivedWithNew : Base
{
    public new void Method()
    {
        Console.WriteLine("I am Dervied");
    }
}

和程序:

var derived = new Derived();
derived.Method(); // I am Dervied
((Base)derived).Method(); // I am Dervied

var derivedWithNew = new DerivedWithNew();
derivedWithNew.Method(); // I am Dervied
((Base)derivedWithNew).Method(); // I am Base <--!!!!!!!!!!!!!!!!!!!
© www.soinside.com 2019 - 2024. All rights reserved.