83

我在(除其他外)这个问题中看到人们想知道如何初始化KeyValuePair的实例,预计应该是这样的。

KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>
{ 
  Key = 1,
  Value = 2
};

它不起作用,好像属性不存在一样。Intead,我需要像这样使用构造函数。

KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);

诚然,语法较短,但令我困扰的是我不能使用初始化程序。我究竟做错了什么?

4

9 回答 9

81

你没有错,你必须使用初始化一个 keyValuePair

KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);

您不能使用对象初始化语法即 { Key = 1, Value = 2 } 的原因是因为 Key 和 Value 属性没有设置器,只有获取器(它们是只读的)。所以你甚至不能这样做:

keyValuePair.Value = 1; // not allowed
于 2013-03-19T09:08:16.547 回答
18

字典有紧凑的初始化器:

var imgFormats = new Dictionary<string, ChartImageFormat>()
{
    {".bmp", ChartImageFormat.Bmp}, 
    {".gif", ChartImageFormat.Gif}, 
    {".jpg", ChartImageFormat.Jpeg}, 
    {".jpeg", ChartImageFormat.Jpeg}, 
    {".png", ChartImageFormat.Png}, 
    {".tiff", ChartImageFormat.Tiff}, 
};

在这种情况下,我用来将文件扩展名与图表对象的图像格式常量相关联的字典。

可以从字典中返回单个键值对,如下所示:

var pair = imgFormats.First(p => p.Key == ".jpg");
于 2017-09-19T22:14:15.733 回答
16

KeyValuePair<int, int>是一个结构体,幸运的是,它是不可变结构体。特别是,这意味着它的属性是只读的。因此,您不能为它们使用对象初始化程序。

于 2013-03-19T09:06:12.303 回答
14

好的,你有答案。作为替代方案,我更喜欢类似于Tuple类的工厂模式,用于类型推断魔法:)

public static class KeyValuePair
{
    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V>(key, value);
    }
}

所以short变得更短:

var keyValuePair = KeyValuePair.Create(1, 2);
于 2013-06-12T20:48:08.810 回答
7

这是一个完成这项工作的例子

KeyValuePair<int, int> kvp = new KeyValuePair<int, int>(1, 1);
于 2015-06-05T20:06:21.160 回答
5

Key 和 Value 属性没有设置器。这就是为什么您不能在初始化程序中使用它们的原因。只需使用构造函数:) 你会没事的。

于 2013-03-19T09:08:43.557 回答
3

我也更喜欢工厂模式。但是当我必须在外面创建一对时,我发现这种方式更有用。这样我就可以支持任何简单到复杂的用例。

这样,我可以使用任何类型并根据其属性或任何我想要的谓词制作 KeyValue Pairs,但更干净。喜欢的方式类似IEnumerable.ToDictionary(keySelector,valueSelector)


        public static KeyValuePair<TKey, TValue> CreatePair<TSource, TKey, TValue>(
         this TSource source,
         Func<TSource, TKey> keySelector, 
         Func<TSource, TValue> valueSelector)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (keySelector is null)
            {
                throw new ArgumentNullException(nameof(keySelector));
            }

            if (valueSelector is null)
            {
                throw new ArgumentNullException(nameof(valueSelector));
            }

            return new KeyValuePair<TKey, TValue>(
                         keySelector.Invoke(source), 
                         valueSelector.Invoke(source));
        }

而你使用。

yourObject.CreatePair(
        x=> x.yourKeyPropery, 
        x=> SomeOperationOnYourProperty(x.yourValueProperty));
于 2020-09-18T09:42:04.753 回答
1

KeyValue属性是只读的,因此您不能在对象初始化程序中使用它们。

请参阅C# 编程指南中的此条目。

于 2013-03-19T09:06:06.410 回答
1

你没有做错什么。KeyValuePairs 属性是只读的。你不能设置它们。此外,没有空的默认构造函数。您需要使用提供的构造函数。

于 2013-03-19T09:06:52.593 回答