问题描述
我(除其他外)见过,人们想知道如何初始化 KeyValuePair 的实例,该实例应该看起来像这样.
I've seen in (amongst others) this question that people wonder how to initialize an instance of KeyValuePair, which expectedly should look like this.
KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>
{
Key = 1,
Value = 2
};
它不起作用,就好像属性不存在一样. Intead,我需要使用这样的构造函数.
It doesn't work, as if the properties aren't there. Intead, I need to use the constructor like this.
KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);
语法较短,但令我困扰的是我无法使用初始化程序.我在做什么错了?
Admittedly shorter syntax but it bothers me that I can't use the initializer. What am I doing wrong?
推荐答案
您没有错,您必须使用以下方法初始化keyValuePair
You are not wrong you have to initialise a keyValuePair using
KeyValuePair<int, int> keyValuePair = new KeyValuePair<int, int>(1, 2);
之所以不能使用对象初始化语法(即{Key = 1,Value = 2}),是因为Key和Value属性没有只有setter的setter(它们是只读的).所以你甚至不能做:
The reason that you cannot use the object initialisation syntax ie { Key = 1, Value = 2 } is because the Key and Value properties have no setters only getters (they are readonly). So you cannot even do:
keyValuePair.Value = 1; // not allowed
这篇关于如何以正确的方式初始化KeyValuePair对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!