zoukankan      html  css  js  c++  java
  • 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);
            }

    把需要的数值类型都得写一遍,其他运算就照这个样子写

  • 相关阅读:
    将requirejs进行到底(一)
    localStorage.ie6.js
    再见,唐家岭!
    彻底理解JavaScript原型
    总结javascript继承的两种方式的N中写法
    Sizzle引擎执行的流程图
    武功唯快不破
    密码强度
    各大浏览器内核(Rendering Engine)
    Angularjs中编写指令模版
  • 原文地址:https://www.cnblogs.com/gxrsprite/p/13534472.html
Copyright © 2011-2022 走看看