为了我的代码,我需要一个元组,它有两个组件,都是KeyValuePairs。然而,对于我的生活,我甚至无法弄清楚如何宣布这件事。我让它使用普通字符串
Tuple<string, string> t = new Tuple<string, string>("abc", "123");
但我需要键值对而不是字符串,我尝试过类似的东西,但它拒绝编译说构造函数不能接受2个参数。
Tuple<KeyValuePair<string, string>, KeyValuePair<string,string>> a =
new Tuple<KeyValuePair<string, string> ("a", "1"),
KeyValuePair<string, string> ("b", "2");
任何指导将不胜感激。如果它对您有帮助,请随意使用:https://dotnetfiddle.net/y2rTlM
使用:
Tuple<KeyValuePair<string, string>, KeyValuePair<string, string>> a =
new Tuple<KeyValuePair<string, string>, KeyValuePair<string, string>>(
new KeyValuePair<string, string>("a", "1"),
new KeyValuePair<string, string>("b", "2")
);
或者,更短一些:
using KVPS = System.Collections.Generic.KeyValuePair<string, string>;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Tuple<KVPS, KVPS> a =
Tuple.Create(
new KVPS("a", "1"),
new KVPS("b", "2")
);
Console.WriteLine($"{a.Item1.Key} {a.Item1.Value} : {a.Item2.Key} {a.Item2.Value}");
}
}
}
如果你有很多元组和类似的元组,这可能会很有用。