首页 > 代码库 > C# 通用区间类

C# 通用区间类

public class Zone<T> where T : IComparable<T>
    {
        /// <summary>
        /// .ctor
        /// </summary>
        public Zone()
        {

        }

        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="briefString">字符串,如("3-5")</param>
        public Zone(string briefString)
        {
            //T min, max;
            string[] arr = briefString.Split(-);
            if (arr.Length == 2)
            {
                if (typeof(T) == typeof(int))
                {
                    Min = (T)(object)(int.Parse(arr[0]));
                    Max = (T)(object)(int.Parse(arr[1]));
                }
                else if (typeof(T) == typeof(decimal))
                {
                    Min = (T)(object)(decimal.Parse(arr[0]));
                    Max = (T)(object)(decimal.Parse(arr[1]));
                }

                Swap();
            }
        }

        /// <summary>
        /// .ctor
        ///  调用如下
        ///  var sdsd = "3-5";
        ///  var zone = new Zone<int>(sdsd, p => int.Parse(p));
        ///  var zone2 = new Zone<decimal>(sdsd, p => decimal.Parse(p));
        /// </summary>
        /// <param name="briefString">字符串,如("3-5")</param>
        /// <param name="converter">转换方法.</param>
        public Zone(string briefString, Converter<string, T> converter)
        {
            //T min, max;
            var arr = briefString.Split(-);
            if (arr.Length == 2)
            {
                Min = converter(arr[0]);
                Max = converter(arr[1]);
                Swap();
            }
        }

        /// <summary>
        /// 小值
        /// </summary>
        public T Min { get; set; }

        /// <summary>
        /// 大值
        /// </summary>
        public T Max { get; set; }

        /// <summary>
        /// ToString()
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("{{Min:{0},Max:{1}}}", Min, Max);
        }

        /// <summary>
        /// 返回简短的String描述
        /// </summary>
        /// <returns></returns>
        public string ToBriefString()
        {
            return string.Format("{0}-{1}", Min, Max);
        }

        private void Swap()
        {
            if (Min.CompareTo(Max) > 0)
            {
                T temp = Max;
                Max = Min;
                Min = temp;
            }
        }
    }

 

C# 通用区间类