using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace 泛型接口
{
    public interface Add<T>
    {
        T add(T x, T y);
    }    class math<T> : Add<T>
    {
        public T add(T x, T y)
        {
            return x + y;
        }
    }    class Program
    {
        static void Main(string[] args)
        {
            math<int> s = new math<int>();
            int z = s.add(4, 7);
            Console.WirteLine(z);
            Console.Read();
        }
    }
}

解决方案 »

  1.   

    问题是:编译该程序的时候会编译失败,错误为-Error Info: 运算符“+”无法应用于“T”和“T”类型的操作数,怎么修改才能让该段代码正常的运行起来呢,请各位帮忙看先,感谢先。。!!
      

  2.   

    是啊T是未知的类型,你把T换成int
      

  3.   

    T 不一定就是你所用的int ,如果是其他类型怎么办?所以整不成的。。
      

  4.   

    如果你就是想做加法的那不如直接把t换成int好了
      

  5.   

    using System;namespace 泛型接口
    {
        public interface Add<T>
        {
            int add(T x, T y);
        }    class math<T> : Add<T>
        where T: IConvertible
        {
            public int add(T x, T y)
            {
                return x.ToInt32(null) + y.ToInt32(null);
            }
        }    class Program
        {
            static void Main(string[] args)
            {
                math<int> s = new math<int>();
                int z = s.add(4, 7);
                Console.WriteLine(z);
                Console.Read();
            }
        }
    }
      

  6.   

    因为在这里T可能为任意的类型,当你自己定义了一个类而又没有重载+操作符时,当然不能成功;
    解决:加入类型约束,把T约束为值类型(public interface Add<T> T where T:struct);或实现了+操作符的派生类型;建议:看看接口约束/派生约束/构造函数约束/引用类型和值类型约束
      

  7.   

    using System;namespace 泛型接口
    {
        public interface Add<T>
        {
            string add(T x, T y);
        }    class math<T> : Add<T>
        where T: IConvertible
        {
            public string add(T x, T y)
            {
                return (x.ToInt32(null) + y.ToInt32(null)).ToString();
            }
        }    class Program
        {
            static void Main(string[] args)
            {
                math<int> s = new math<int>();
                int z = int.Parse(s.add(4, 7));
                Console.WriteLine(z);
                Console.Read();
            }
        }
    }
      

  8.   


    1、struct并没有实现+操作符,所以添加此约束并不能解决问题;
    2、如果你自定义一个含+操作符的接口,那就不能用int,float等值类型去实例化,因为它们并没有继承你的接口。