简体   繁体   English

具有受限Type参数的泛型类

[英]Generic class with restricted Type parameter

I want to create a generic class that takes a type parameter and restrict that parameter to numeric types or more generally to any type upon which the increment operator ++ can be applied. 我想创建一个泛型类,它接受一个类型参数并将该参数限制为数值类型,或者更一般地限制为可以应用增量运算符++的任何类型。

I know I can do the following to restrict to structs but obviously there are structs that aren't numeric types and for which the ++ operator is not supported. 我知道我可以执行以下操作来限制结构但显然有些结构不是数字类型,并且不支持++运算符。 Can I do this in C# 我可以用C#做​​这个吗

class Example<T> where T : struct
{
  //Implementation detail
}

Unfortunately this is not possible (see here .) You can only constrain the type to: 不幸的是,这是不可能的(请参阅此处 。)您只能将类型约束为:

  • Implement a specific interface or derive from a specific class 实现特定接口或从特定类派生
  • Be a class or struct 是一个classstruct
  • Have a parameterless constructor 有一个无参数的构造函数

Constraining types to have specific operators is a much-requested feature but I believe it will not be in C# 4 either. 约束类型以具有特定的运算符是一个非常需要的功能,但我相信它也不会在C#4中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM