泛型的where参数可不可以支持整数/浮点数等基本类型
泛型的where参数能否支持整数/浮点数等基本类型?
我希望能用泛型来写一个函数,能够让我接受整数类型和浮点数类型,而不接受其他类型的参数,如下:
但是有编译错误:
Error 1 'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. D:\Documents\Visual Studio 2013\Projects\ConsoleApplication1\ConsoleApplication3\Program.cs 11 45 ConsoleApplication3
我想问,C#的这个限制到底是为了要做什么呢? 我希望能否限制使用哪些类型,但是where本身为什么还有这么多限制呢?
谢谢。
------解决思路----------------------
首先,泛型约束中,多个约束是AND的关系,不是OR的关系,因此不能叨叨你要约束为int或short或byte的目的。
其次,约束为最终类型没有意义(既然有了最终类型,就没有泛型的需要了),因此约束:
不能是具体结构,因为没有其它类型可以继承结构
不能是密封类(sealed class),同样因为不能继承密封类。
------解决思路----------------------
只能用重载来实现
------解决思路----------------------
约束不是万能……只能struct……
你这种还是重载吧
------解决思路----------------------
where T : struct
------解决思路----------------------
T必须是一个结构类型
where T : class T必须是一个类(class)类型
where T : new()
------解决思路----------------------
T必须要有一个无参构造函数
where T : BaseClass
------解决思路----------------------
T必须继承指定基类
where T : Interface
------解决思路----------------------
T必须实指定接口
where约束就以上集中,where约束不用于基础类型。
我希望能用泛型来写一个函数,能够让我接受整数类型和浮点数类型,而不接受其他类型的参数,如下:
class Program
{
public void F<T>(T input) where T : int, short, byte
{
Console.WriteLine(input);
}
static void Main(string[] args)
{
Program.F<int>(3);
}
}
但是有编译错误:
Error 1 'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. D:\Documents\Visual Studio 2013\Projects\ConsoleApplication1\ConsoleApplication3\Program.cs 11 45 ConsoleApplication3
我想问,C#的这个限制到底是为了要做什么呢? 我希望能否限制使用哪些类型,但是where本身为什么还有这么多限制呢?
谢谢。
------解决思路----------------------
首先,泛型约束中,多个约束是AND的关系,不是OR的关系,因此不能叨叨你要约束为int或short或byte的目的。
其次,约束为最终类型没有意义(既然有了最终类型,就没有泛型的需要了),因此约束:
不能是具体结构,因为没有其它类型可以继承结构
不能是密封类(sealed class),同样因为不能继承密封类。
------解决思路----------------------
只能用重载来实现
------解决思路----------------------
约束不是万能……只能struct……
你这种还是重载吧
------解决思路----------------------
where T : struct
------解决思路----------------------
T必须是一个结构类型
where T : class T必须是一个类(class)类型
where T : new()
------解决思路----------------------
T必须要有一个无参构造函数
where T : BaseClass
------解决思路----------------------
T必须继承指定基类
where T : Interface
------解决思路----------------------
T必须实指定接口
where约束就以上集中,where约束不用于基础类型。