假设我们有一个这样工作的程序:
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 theMainStorage
object or does it make a reference to it?
它复制了对 Storage
实例的引用。在这种情况下,PrintData
中的字段将引用内存中与您分配给 MainStorage
的实例相同的实例。
您可以通过检查类型是class
还是struct
来检查赋值是否具有引用语义。如果它是值类型 (struct
),则副本将具有值复制语义。
关于c# - 如何判断一个值是被复制还是被引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714077/