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();
}
}
}
解决方案 »
- Silverlight4+WCF RIA Service+EF出现问题了啊!!!
- C#后台调用JAVA后台 得到JAVA后台运算出来的一个字符串
- 求获得硬盘序列号(物理)的方法
- 怎样把\替换成\\
- 寻找一个c#读取远程数据库的代码
- 请问html数据能否载入到Document对象里面做dom处理..
- 求助在win2003server中css在.aspx不能正确显示的问题?太奇怪了
- 如何清除文件的内容? 请教
- 我自己开发的服务去哪里了??郁闷!!!!!!!
- 在datagradView中验证输入数据是否合符类型之后,如何让错误的数据恢复到原来未编辑的数据
- 自己写的dll组件如何加密?
- 请教C#如何调用用其软件开发出来小软件??
{
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();
}
}
}
解决:加入类型约束,把T约束为值类型(public interface Add<T> T where T:struct);或实现了+操作符的派生类型;建议:看看接口约束/派生约束/构造函数约束/引用类型和值类型约束
{
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();
}
}
}
1、struct并没有实现+操作符,所以添加此约束并不能解决问题;
2、如果你自定义一个含+操作符的接口,那就不能用int,float等值类型去实例化,因为它们并没有继承你的接口。