When I change the value of a variable which is a copy of another, it changes the original variable also

后端 未结 2 968
悲哀的现实
悲哀的现实 2021-01-13 12:04
public class TestClass
{
    public int TestNumber;
    public string TestName;

    public TestClass(string name, int number)
    {
        TestName   = name;
              


        
相关标签:
2条回答
  • 2021-01-13 12:19

    C# is a pass by reference language, when dealing with objects. So when you say Var2 = Var, you're saying that Var2 now holds the address of whatever address Var1 was holding, effectively making them point to the same object.

    One work around is to turn it into a pass by value, like so:

    public void Start()
    {
        Var1 = new TestClass("Me", 1);
        Var2 = new TestClass();           // You would need a default constructor, and to use it to prevent the null exception error
    
        Var2.TestNumber = Var1.TestNumber;
        Var2.TestName   = "aaa";
    
    }
    

    Or, if you will be using more values and this is an overly simplified example, you can use another approach:

    public void Start()
    {
        Var1 = new TestClass("Me", 1);
        Var2 = Var1.GetValues();
    }
    

    And in your test class:

    public testClass GetValues() => return new testClass(TestNumber, TestName);
    
    0 讨论(0)
  • 2021-01-13 12:29

    Here is your problem:

    Var1=new TestClass("Me",1);
    Var2 = Var1;
    Var2.TestName="aaa";
    

    Var2 = Var1; is actually a reference copy! This means that the Var2 will take the address of Var1 and no matter what you modify in either of them, it will be visible in the other. To get that, I would recommend using a copy of Var2. To do so, create a method in your testClass class.

    public testClass copy()
    {
        testClass tC = new testClass(this.TestNumber, this.TestName);
        return tC;
    }
    

    Now you can assign the value like this: Var2 = Var1.copy();

    0 讨论(0)
提交回复
热议问题