C#使用对象(应该是byRef Byval问题)

时间:2018-10-03 09:03:58

标签: c#

我有我的Compressors类:

public class Compressors
{

    public Refrigerant Output { get; set; }
    public Refrigerant Input { get; set; }


// Constructor
    public Compressors(Refrigerant input)
    {
        Input = input; 
    }

}

在我的主要代码中,我有:

var Compressor1 = new Compressors(BeforeComp);
var Compressor2 = new Compressors(Compressor1.Output);

看着很好

Compressor1.Input
Compressor1.Output

但是看着

Compressor2.Input //Should be the same as Compressor1.Output!

返回Null错误

总结一下,我希望Compressor1.Output和Compressor2.Input引用同一对象。 我在做什么错了?

2 个答案:

答案 0 :(得分:1)

代码按预期运行。
您永远不会初始化Compressor1.Output。因此,它是null。您可以将此值用作Compressor2的构造函数的输入,这就是您随后将在Compressor2.Input中看到的值。

换句话说:

Assert.Equal(Compressor1.Output, Compressor2.Input);
Assert.Null(Compressor1.Output);
Assert.Null(Compressor2.Input);

答案 1 :(得分:0)

感谢您的反馈!它让我看向其他地方

我用了这个:

public Refrigerant ShallowCopy()
{
return (Refrigerant)this.MemberwiseClone();
}

复制存储在我的制冷剂类中的值。 我以为这只会复制值,所以我不必

Output.x = Input.x
Output.y = Input.y
Output.z = Input.z

但是它没有按预期工作