是否可以存储对类实例的引用?
class Node
{
public int id;
public int value;
public List<Node> neighbours;
}
我如何填充列表 neighbors
以便我对 Node
实例所做的任何更改都会反射(reflect)在那里?
最佳答案
public List<Node> neighbours;
由于您的 Node
类是引用类型所有变量类型 Node
将只包含对 Node
的引用(就像一个指针)内存中的对象 - 因此邻居列表包含对您的 Node
的引用列表对象 - 对这些对象的任何更改都将反射(reflect)在列表中,因为它们指向您修改的对象。
另见 Value Types and Reference Types :
A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data.
编辑以解决评论:
如前所述,您的 Node
类是引用类型,所有类类型都是。我引用自 MSDN再次:
Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.
现在这对您意味着什么? struct
的大小类型是其成员的组合大小,它不指向内存地址,不像 class
类型。使用 struct
将改变你的类型行为的语义 - 如果你将一个结构实例分配给另一个相同类型的实例(对于任何其他值类型相同),struct
中的所有值将从一个复制到另一个,您仍然有两个单独的对象实例。 - 另一方面,对于引用类型,之后两者都会指向同一个对象。
示例 节点是一个 class
:
Node node1 = new Node() { id = 1, value = 42};
Node node2 = node1;
node2.value = 55;
Console.WriteLine(node1.value); //prints 55, both point to same,modified object
示例 节点是一个 struct
:
Node node1 = new Node() { id = 1, value = 42};
Node node2 = node1;
node2.value = 55;
Console.WriteLine(node1.value); //prints 42, separate objects
关于c# - C#中指向类实例的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5444112/