(C#) How to copy classes by value type and not reference type?

做~自己de王妃 提交于 2021-02-10 06:40:28

问题


Take the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass
{
    public int myNumber;
}

public class Test : MonoBehaviour
{
    MyClass class1 = new MyClass();
    MyClass class2 = new MyClass();

    void Start()
    {
        class1.myNumber = 1;
        class2 = class1;
        class2.myNumber = 2;

        Debug.Log(class1.myNumber); //output: 2 (I'd want it to output 1!!!)
    }
}

Now, if I understood correctly, in C# classes are a reference type and not a value type, so this behavior is desired.
However, what would I need to do to not make it so? What could I do to make a normal value assignment without "linking" the two classes together?

I realize I could replace line 18 with this:

class2.myNumber = class1.myNumber;

And it would do what I want (since I'm assigning a value type and not a reference type), but it's kinda inconvenient for my case... in my real script the class has several sub-elements that I need to copy in many different places.

Is there a one-line method to copy a class to a new one, without it being linked by reference to the original one but by creating a new independent class?


回答1:


Perform a Deep or Shallow Copy depending on your needs. https://docs.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8




回答2:


C# has something called a Struct which is basically a lightweight version of a Class that is a value type. If you specifically need a value type you might want to use Structs instead of Classes.

Main differences are Structs don't need to be instantiated using a "New" assignment, they cannot inherit from another Struct or Class and they cannot be used as the base for another Class.




回答3:


How about this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass
{
    public int myNumber;
}

public class Test : MonoBehaviour
{
    MyClass class1 = new MyClass();
    MyClass class2 = new MyClass();

    private void Start()
    {
        class1.myNumber = 1;
        class2 = GetClassCopy(class1);
        class2.myNumber = 2;
        Debug.Log(class1.myNumber); // output:1
    }

    private MyClass GetClassCopy(MyClass source)
    {
        MyClass result = new MyClass();
        result.myNumber = source.myNumber;
        return result;
    }
}


来源:https://stackoverflow.com/questions/61232406/c-how-to-copy-classes-by-value-type-and-not-reference-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!