Is it possible for a function to return two values?

后端 未结 13 1485
谎友^
谎友^ 2020-12-31 08:41

Is it possible for a function to return two values? Array is possible if the two values are both the same type, but how do you return two different type values?

13条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 09:37

    To return 2 values I usually use Pair class from http://blog.o-x-t.com/2007/07/16/generic-pair-net-class/. If you need to return from method 2 values that describe the range, e.g. From/To or Min/Max, you can use FromToRange class.

    public class FromToRange
        {
            public T From { get; set; }
            public T To { get; set; }
    
            public FromToRange()
            {
            }
    
            public FromToRange(T  from, T  to)
            {
                this.From = from;
                this.To = to;
            }
            public override string ToString()
            {
                string sRet = String.Format("From {0} to {1}", From, To);
                return sRet;
            }
            public override bool Equals(object obj)
            {
                if (this == obj) return true;
                FromToRange pair = obj as FromToRange;
                if (pair == null) return false;
                return Equals(From, pair.From) && Equals(To, pair.To);
            }
    
            public override int GetHashCode()
            {
                return (From != null ? From.GetHashCode() : 0) + 29 * (To != null ? To.GetHashCode() : 0);
            }
    
        }
    

提交回复
热议问题