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

前端 未结 14 1931
情话喂你
情话喂你 2020-11-29 16:54

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.

Than

相关标签:
14条回答
  • 2020-11-29 17:22

    The PowerCollections library (formerly available from Wintellect but now hosted on Codeplex @ http://powercollections.codeplex.com) has a generic Pair structure.

    0 讨论(0)
  • 2020-11-29 17:23

    Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

    Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
    

    and access values through t.Item1 and t.Item2, you can simply do it like that:

    (string message, int count) = ("Hello", 4);
    

    or even:

    (var message, var count) = ("Hello", 4);
    
    0 讨论(0)
  • 2020-11-29 17:28

    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.

    0 讨论(0)
  • 2020-11-29 17:28

    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.

    0 讨论(0)
  • 2020-11-29 17:30

    I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework

    0 讨论(0)
  • 2020-11-29 17:32

    C# has tuples as of version 4.0.

    0 讨论(0)
提交回复
热议问题