如何在 C# 中实例化泛型类型的 linkedlistNode

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

例如我有一个通用的 class KeyAndValue

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

现在我想实例化一个 LinkedListNode<KeyAndValue<int, int>> 对象

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

我收到了这样的警告

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

我的问题是如何创建泛型类型的泛型对象?

您可以使用现有的 class KeyValuePair 而不是 KeyAndValue。另外你可以创建一个构造函数:

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; }
    }

两者皆有可能:

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);