C#泛型的加法運算方法


有的時候會把double int這類數值放在泛型方法里,就不需要寫多份了,但是這個時候也需要進行四則運算,可以寫成這個樣子

 

public static T Add<T>(T num1, T num2) where T : struct, IComparable
        {
            if (typeof(T) == typeof(int))
            {
                int a = (int)Convert.ChangeType(num1, typeof(int));
                int b = (int)Convert.ChangeType(num2, typeof(int));

                int c = a + b;
                return (T)Convert.ChangeType(c, typeof(T));
            }
            else if (typeof(T) == typeof(float))
            {
                float a = (float)Convert.ChangeType(num1, typeof(float));
                float b = (float)Convert.ChangeType(num2, typeof(float));

                float c = a + b;
                return (T)Convert.ChangeType(c, typeof(T));
            }
            else if (typeof(T) == typeof(double))
            {
                double a = (double)Convert.ChangeType(num1, typeof(double));
                double b = (double)Convert.ChangeType(num2, typeof(double));

                double c = a + b;
                return (T)Convert.ChangeType(c, typeof(T));
            }
            else if (typeof(T) == typeof(decimal))
            {
                decimal a = (decimal)Convert.ChangeType(num1, typeof(decimal));
                decimal b = (decimal)Convert.ChangeType(num2, typeof(decimal));

                decimal c = a + b;
                return (T)Convert.ChangeType(c, typeof(T));
            }

            return default(T);
        }

 

把需要的數值類型都得寫一遍,其他運算就照這個樣子寫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM