开发者

Pointer to a class instance in C#

Is it possible to store the reference to a class instance?

class Node
{
    public int id;
    public int value;
    public List<Node&开发者_如何学JAVAgt; neighbours;
}

How do I populate the list neighbours in such a way that any changes I make to a Node instance will be reflected there ?


public List<Node> neighbours;

Since your Node class is a reference type all variables of type Node will only contain references (just like a pointer) to a Node object in memory - so the neighbours list contains a list of references to your Node objects- any change to those objects will be reflected in the list, since they point to the objects that you modified.

Also see 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.

Edit to address comment:

As mentioned your Node class is a reference type, all class types are. I quote from MSDN again:

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.

Now what does that mean for you? The size of a struct type is the combined size of its members, it does not point to a memory address, unlike the class type. Using a struct will change the semantics of your type's behavior - if you assign one struct instance to another of the same type (same for any other value type), all values in the struct will be copied from one to the other, you still have two separate object instances. - for a reference type on the other hand both would point to the same object afterwards.

Example Node is a 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

Example Node is a struct:

Node node1 = new Node() { id = 1, value = 42};
Node node2 = node1;

node2.value = 55;
Console.WriteLine(node1.value); //prints 42, separate objects


If you have

Node node = new Node{Id =1, Value = 1};
node.neighbours = new List<Node>();
Node neighbourNode = new Node{Id =1, Value = 1};
node.neighbours.Add(neighbourNode);

you can change neighbourNode after adding it to node and since you are storing the reference, it will be reflected in the list's item.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜