简体   繁体   English

Ref Class vs Ref Struct,有什么区别?

[英]Ref Class vs Ref Struct, what's the difference?

public struct StructHouse{
public int number;
}


public class ClassHouse{
public int number;
}


public class Test{
public TestForStruct testForStruct;
public ClassHouse classHouse = new ClassHouse();
public StructHouse structHouse = new StructHouse();

SendRef1(ref classHouse);
testForStruct.SendRef2(ref structHouse);
}

public class TestForStruct{
public StructHouse structHouse;

public void (ref classHouse);
public void SendRef2(ref StructHouse structHouse){
this.structHouse = structHouse;
this.structHouse.number = 1;      //THIS DOESN'T UPDATE THE VALUE FOR 'Test'
//BUT IT DOES UPDATE IF I SEND REF CLASS INSTEAD OF REF STRUCT
}

e: if I change the reference value for 'number' in 'SendRef1', the value is updated in the class Test, but it's not updated when changing the value in SendRef2. e:如果我更改了“ SendRef1”中“数字”的参考值,则该值将在Test类中更新,但在SendRef2中更改该值时不会更新。 Can anyone please explain this? 谁能解释一下?

Thanks in advance. 提前致谢。

This line is copying the struct. 此行正在复制结构。

this.structHouse = structHouse;

You change the value of number only on the copy. 您只能在副本上更改number的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM