简体   繁体   中英

How to instantiate a linkedlistNode of a generic type in c#

For example I have a generic class KeyAndValue

public class KeyAndValue<T, U>
{
    public T? key { get; set; }
    public U? value { get; set; }
}

Now I want to instantiate a LinkedListNode<KeyAndValue<int, int>> object

var newNode = new LinkedListNode<KeyAndValue<int, int>>();

I received warning like this

There is no argument given that corresponds to the required formal parameter 'value' of 'LinkedListNode<KeyAndValue<int, int>>.LinkedListNode(KeyAndValue<int, int>)' [146]",

My question is how to create an object that is generic type of generic type?

You can use the existing class KeyValuePair instead of KeyAndValue . Additional you can create a constructor:

public class KeyAndValue<T, U>
    {
        public KeyAndValue(T key, U value)
        {
            this.key = key;
            this.value = value;
        }
        public T? key { get; set; }
        public U? value { get; set; }
    }

Both is possible:

var keyValuePair = new KeyValuePair<int, int>(0, 5);
var linkedListNode1 = new LinkedListNode<KeyValuePair<int, int>>(keyValuePair);

var keyAndValue = new KeyAndValue<int, int>(0, 5);
var linkedListNode2 = new LinkedListNode<KeyAndValue<int, int>>(keyAndValue);

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