What is C# analog of C++ std::pair?

2019-01-07 03:38发布

I'm interested: What is C#'s analog of std::pair in C++? I found System.Web.UI.Pair class, but I'd prefer something template-based.

Thank you!

14条回答
戒情不戒烟
2楼-- · 2019-01-07 04:21

Unfortunately, there is none. You can use the System.Collections.Generic.KeyValuePair<K, V> in many situations.

Alternatively, you can use anonymous types to handle tuples, at least locally:

var x = new { First = "x", Second = 42 };

The last alternative is to create an own class.

查看更多
迷人小祖宗
3楼-- · 2019-01-07 04:22

On order to get the above to work (I needed a pair as the key of a dictionary). I had to add:

    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);
    }

and once I did that I also added

    public override Int32 GetHashCode()
    {
        return First.GetHashCode() ^ Second.GetHashCode();
    }

to suppress a compiler warning.

查看更多
登录 后发表回答