简体   繁体   中英

.Net - How are LinkedListNode<T>'s Properties assigned to?

According to both the documentation and metadata for .Net's LinkedListNode<T> class, its List , Next and Previous properties are get-only. However, LinkedList<T> somehow manages to alter these properties.

How does LinkedList<T> achieve this?

Is it using reflection or is it cheating by using internal setters?

Here are the fields of LinkedListNode<T> :

public sealed class LinkedListNode<T> {
    internal LinkedList<T> list;
    internal LinkedListNode<T> next;
    internal LinkedListNode<T> prev;
    internal T item;

    // ...
}

As you can see, the fields are internal, and as such they can be manipulated by the LinkedList<T> (or by any other class in the System assembly for that matter), but you can't do that from your code.

An example :

private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) {
    newNode.next = node;
    newNode.prev = node.prev;
    node.prev.next = newNode;
    node.prev = newNode;            
    version++;
    count++;
}

The fields list , prev and next in LinkedListNode<T> are marked with the internal access modifier. Internal types/members are accessible only to other types in the same assembly. In this case, both LinkedListNode<T> and LinkedList<T> are in the System assembly.

If we look at how they are actually defined:

public sealed class LinkedListNode<T>
{
  internal LinkedList<T> list;
  internal LinkedListNode<T> next;
  internal LinkedListNode<T> prev;
  internal T item;
  ....
}

One can always change data within the same class even if its get-only property

Refer to below example:

class Property
{
    private string _name = "_name";
    public string Name
    {
        get
        {
            return _name;
        }
    }

    public void Foo()
    {
        _name = "foo";
    }


    static void Main(string[] args)
    {
        Property prop = new Property();

        Console.WriteLine(prop.Name);  // prints _name

        prop.Foo();

        Console.WriteLine(prop.Name); // prints foo
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM