我已经看到(其中包括)this question人们想知道如何初始化 KeyValuePair 的实例,预计应该看起来像这样。
KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>
{
Key = 1,
Value = 2
};
它不起作用,好像属性不在那里。 Intead,我需要像这样使用构造函数。
KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);
不可否认,语法较短但令我困扰的是我无法使用初始化程序。我做错了什么?
答案 0 :(得分:46)
你没有错,你必须使用
初始化keyValuePairKeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);
你不能使用对象初始化语法即{Key = 1,Value = 2}的原因是Key和Value属性没有setter only getter(它们只读)。所以你甚至不能这样做:
keyValuePair.Value = 1; // not allowed
答案 1 :(得分:13)
KeyValuePair<int, int>
是一个结构,幸运的是,它是 immutable 结构。特别是,这意味着它的属性是只读的。因此,您无法使用对象初始化程序。
答案 2 :(得分:9)
好的,你有答案。作为替代方案,我更喜欢类似于Tuple
类的工厂模式,用于类型推理魔术:)
public static class KeyValuePair
{
public static KeyValuePair<K, V> Create<K, V>(K key, V value)
{
return new KeyValuePair<K, V>(key, value);
}
}
如此短暂变短:
var keyValuePair = KeyValuePair.Create(1, 2);
答案 3 :(得分:7)
字典具有紧凑的初始值设定项:
var imgFormats = new Dictionary<string, ChartImageFormat>()
{
{".bmp", ChartImageFormat.Bmp},
{".gif", ChartImageFormat.Gif},
{".jpg", ChartImageFormat.Jpeg},
{".jpeg", ChartImageFormat.Jpeg},
{".png", ChartImageFormat.Png},
{".tiff", ChartImageFormat.Tiff},
};
在这种情况下,我用来将文件扩展名与图表对象的图像格式常量相关联。
可以从字典中返回单个keyvaluepair,如下所示:
var pair = imgFormats.First(p => p.Key == ".jpg");
答案 4 :(得分:5)
Key和Value属性没有setter。这就是为什么你不能在初始化器中使用它们。只需使用构造函数:),你会没事的。
答案 5 :(得分:3)
这是一个完成工作的例子
KeyValuePair<int, int> kvp = new KeyValuePair<int, int>(1, 1);
答案 6 :(得分:2)
我也更喜欢工厂模式。但是当我不得不在外面创建一对时,我发现这种方法会更加有用。这样,我可以支持任何简单到复杂的用例。
这样,我可以使用任何Type并从其属性或我想要的任何谓词中创建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));
答案 7 :(得分:1)
答案 8 :(得分:1)
你没有做错事。 KeyValuePairs属性是只读的。你不能设置它们。此外,没有空的默认构造函数。您需要使用提供的构造函数。