(C#) 如何按值类型而不是引用类型复制类? [英] (C#) How to copy classes by value type and not reference type?

查看:37
本文介绍了(C#) 如何按值类型而不是引用类型复制类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取以下代码:

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!!!)
    }
}

现在,如果我理解正确的话,在 C# 中,类是引用类型而不是值类型,因此需要这种行为.
但是,我需要做什么才能不这样做?我该怎么做才能在不将两个类链接"在一起的情况下进行正常的值分配?

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?

我意识到我可以用这个替换第 18 行:

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?

推荐答案

根据您的需要执行深拷贝或浅拷贝.https://docs.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8

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

这篇关于(C#) 如何按值类型而不是引用类型复制类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆