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

指向C#中的类实例的指针,第1张

概述是否可以将引用存储到类实例中? class Node{ public int id; public int value; public List<Node> neighbours;} 如何以这样的方式填充列表邻居:我对Node实例所做的任何更改都将反映在那里? public List<Node> neighbours; 由于Node类是引用类型,所以Node类型的所有变 是否可以将引用存储到类实例中?

class Node{    public int ID;    public int value;    public List<Node> neighbours;}

如何以这样的方式填充列表邻居:我对Node实例所做的任何更改都将反映在那里?

解决方法
public List<Node> neighbours;

由于Node类是引用类型,所以Node类型的所有变量都只包含对内存中Node对象的引用(就像指针一样) – 因此邻居列表包含对Node对象的引用列表 – 对这些对象的任何更改都将反映在列表中,因为它们指向您修改的对象.

另见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类是引用类型,所有类类型都是.我再次引用@L_502_1@:

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.

那对你来说意味着什么?结构类型的大小是其成员的组合大小,与类类型不同,它不指向内存地址.使用结构将改变类型行为的语义 – 如果您将一个结构实例分配给另一个相同类型的结构(对于任何其他值类型相同),结构中的所有值将从一个复制到另一个,您仍然具有两个单独的对象实例. – 另一方面,对于参考类型,两者都会指向同一个对象.

示例节点是一个类:

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

示例Node是一个结构:

Node node1 = new Node() { ID = 1,value = 42};Node node2 = node1;node2.value = 55;Console.Writeline(node1.value); //prints 42,separate objects
总结

以上是内存溢出为你收集整理的指向C#中的类实例的指针全部内容,希望文章能够帮你解决指向C#中的类实例的指针所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1224741.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存