c# - C#中指向类实例的指针

标签 c# pointers

是否可以存储对类实例的引用?

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/

相关文章:

c# - ContentControl 和 CollectionView.CurrentItem

c# - 给定类型 ExpressionType.MemberAccess,如何获取字段值?

c - 用 C 语言编写打印方法

css - 在没有 Javascript 的情况下获取鼠标指针在 CSS 中的位置

c - C 中的段错误。尝试使用指针交换两个值

c - 从函数返回 int 类型数组的问题

c# - 在图表上显示 X 和 Y 值的数据点

c# - XML 序列化 : 64Bit Windows7, oct 处理器核心,32GB RAM 和 OutOfMemory 异常

c# - 使用 C# 将 Xml 反序列化为 List<T>

c - 如何将指向动态分配数组的指针作为函数参数传输