C# 使用自定义的泛型函数⼀方法对泛型数组进行四则运算

2024-11-28 08:36:05
推荐回答(4个)
回答1:

static void GetSum(T[] a)
        {
            if (a == null)
            {
                Console.WriteLine("无意义");
                return;
            }

            if (a is int[])
            {
                int sum = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    sum += Convert.ToInt32(a[i]);
                }
                Console.WriteLine(sum);
            }
            else if (a is double[])
            {
                double sum = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    sum += Convert.ToDouble(a[i]);
                }
                Console.WriteLine(sum);
            }
            else if (a is float[])
            {
                float sum = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    sum += Convert.ToSingle(a[i]);
                }
                Console.WriteLine(sum);
            }
        }

 //使用时:
int[] a ={ 1, 2, 3, 4 };
             GetSum(a);
             //本来是想返回T类型的 结果一直无法实现

回答2:

        static void Main(string[] args)
        {
            Console.WriteLine(sum(1, 2));
            Console.ReadLine();
        }

        public static T sum(T a, T b) where T : struct
        {
            string ts = typeof(T).ToString();
            switch (ts.Substring(ts.LastIndexOf(".") + 1))
            {
                case "Int32"://示例,只写了整数
                    {
                        int sum = Convert.ToInt32(a) + Convert.ToInt32(b);
                        return (T)Convert.ChangeType(sum, typeof(T));
                    }
                default://只是为了防止编译错误
                    {

                        return (T)(new object());
                    }
            }
        }

回答3:

static T Sum(params T[] arrays) where T : struct
        {
            if (arrays.Length > 0)
            {
                dynamic sum = default(T);
                foreach (T memb in arrays)
                    sum += memb;
                return sum;
            }
            else
                throw new System.IndexOutOfRangeException();
        }

回答4:

dynamic动态类型