日期:2014-05-17  浏览次数:20855 次

泛型约束问题
        /// <summary>
        /// 累加数组中所有数字
        /// </summary>
        /// <typeparam name="T">所有数字类型</typeparam>
        /// <param name="a">数组</param>
        /// <returns>数字</returns>
        public static double Sum<T>(T[] a) where T : sbyte, byte, short, ushort, int, uint, long, ulong, float, double {
            double s = 0;
            for (int i = 0; i < a.Length; i++) {
                s += Double.Parse( a[i].ToString());
                
            }
            return s;
        }

错误  “sbyte”不是有效的约束。作为约束使用的类型必须是接口、非密封类或类型形参。

我想对这个约束为数字怎么写?

------解决方案--------------------
约束不能指定为int、double这种,按你的需求,只能写成
public static double Sum<T>(T[] a) where T : struct
------解决方案--------------------
        public static double Sum<T>(T[] a) where T : struct
        {
            double s = 0;
            for (int i = 0; i < a.Length; i++)
            {
                ValueType value = a[i] as ValueType;
                if (value != null && (value is Byte 
------解决方案--------------------

               value is Int16 
------解决方案--------------------

               value is Int32 
------解决方案--------------------

               value is Int64 
------解决方案--------------------

               value is SByte 
------解决方案--------------------

               value is UInt16