c# - 如何判断一个值是被复制还是被引用?

标签 c# .net reference value-type reference-type

假设我们有一个这样工作的程序:

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Storage MainStorage = new Storage();

            PrintData Printer = new PrintData();

            Printer.GetStorage(MainStorage);
        }
    }

    class Storage
    {
        //Stores some data
    }

    class PrintData
    {
        Storage storage;

        public void GetStorage(Storage storage)
        {
            this.storage = storage;
        }

        public void Print()
        {
            //Prints data
        }
    }
}

这只是一个示例,所以代码不会完美,但我的问题是在这种情况下,GetStorage() 方法是否复制了 MainStorage 对象,或者是否这样做引用它?

最佳答案

Its just an example so the code wont be perfect but my question is in this instance does the GetStorage() method make a copy of the MainStorage object or does it make a reference to it?

它复制了对 Storage 实例的引用。在这种情况下,PrintData 中的字段将引用内存中与您分配给 MainStorage 的实例相同的实例。

您可以通过检查类型是class 还是struct 来检查赋值是否具有引用语义。如果它是值类型 (struct),则副本将具有值复制语义。

关于c# - 如何判断一个值是被复制还是被引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714077/

相关文章:

c# - 验证文件后错误无效的 json 原语

c# - MVC 中的奇怪异常

c# - 使用 Linq to XML、XMLNS、XDeclaration、单元格格式创建 Office Excel 文档(有效)

c# - 大型 RegEx 匹配导致程序挂起

c# - 如何将 Windows 服务安装到另一个系统?

c++ - 此 C++ 代码是否正确(从枚举标识符创建引用)?

c# - 使用泛型编写类似的逻辑

c# - 如何启动未提升的进程

c++ - 在 C++ 中重命名一个类

c++ - 如何将指针转换为引用?