我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
当前回答
c#在4.0版就有了元组。
其他回答
不幸的是,没有。你可以使用System.Collections.Generic。KeyValuePair<K, V>在许多情况下。
或者,你可以使用匿名类型来处理元组,至少在本地:
var x = new { First = "x", Second = 42 };
最后一种选择是创建自己的类。
为了让上面的工作(我需要一对作为字典的键)。我必须补充一句:
public override Boolean Equals(Object o)
{
Pair<T, U> that = o as Pair<T, U>;
if (that == null)
return false;
else
return this.First.Equals(that.First) && this.Second.Equals(that.Second);
}
一旦我这样做了,我还添加了
public override Int32 GetHashCode()
{
return First.GetHashCode() ^ Second.GetHashCode();
}
禁用编译器警告。
c#在4.0版就有了元组。
如果是关于字典之类的,你要找System.Collections.Generic。KeyValuePair < TKey, TValue >。
元组从。net 4.0开始就可用了,并且支持泛型:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
在以前的版本中,您可以使用System.Collections.Generic。KeyValuePair<K, V>或如下解:
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
像这样使用它:
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
这个输出:
test
2
或者甚至是这个链对:
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;
Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
输出:
test
12
true