简体   繁体   English

约束类型允许C#中的加/减操作(+/-)

[英]Constrain type to allow addition/subtraction operations (+/-) in C#

Is this possible? 这可能吗?

public interface Foo<TBar>
  where TBar : (can use the '+' and '-' operators)

Thanks. 谢谢。

You can create a type Foo that overloads those two operators and then constrain your generic type to it. 您可以创建一个类型Foo ,重载这两个运算符,然后将您的泛型类型约束到它。 You cannot however constrain your generic parameter to require that any arbitrary type overloads such operators on an ad-hoc basis. 但是,您不能将通用参数限制为要求任意类型在临时基础上重载此类运算符。

Yes and No. A generic parameter can only be constrained to 是和否。通用参数只能限制为

  • Implement an inerface 实现一个表面
  • Have an accessible parameterless constructor ( new() ) 有一个可访问的无参数构造函数( new()
  • Have a particular base type 有一个特定的基本类型
  • Be a struct / class 是一个结构/类

The only one of these which is useful for + and - operators is the base type. 对于+-运算符唯一有用的是基类型。 So if the base type contains these operators you can constrain your TBar to also implement them. 因此,如果基类型包含这些运算符,您可以限制TBar也实现它们。

However this doesn't work in the general sense. 然而,这在一般意义上不起作用。 No matter what base type you choose it will fail to work with the types which are most commonly used with + and - . 无论您选择哪种基类型,它都将无法使用最常用于+- Namely int , double , string , etc ... because they inherit from ValueType which doesn't have this constraint intdoublestring等...因为它们从ValueType继承而没有此约束

You can overload the operators: 您可以重载运算符:

public static TBar operator +(TBar c1, TBar c2) 
{
   return ... // do the math
}

No, it is not possible. 不,这是不可能的。

You could, in theory, constraint TBar to of a type that implements those operators, but operators are static, they're not inherited. 理论上,您可以将TBar约束为实现这些运算符的类型,但运算符是静态的,它们不是继承的。

Which means that you would effectively constrain your type to be only the base type, in which case you could drop generics altogether. 这意味着您可以有效地将类型限制为基类型,在这种情况下,您可以完全删除泛型。

And no, you can't constrain your TBar generic parameter to be "any type that implements those operators", it's just not available in the language. 不,你不能将你的TBar通用参数限制为“任何实现这些运算符的类型”,它只是在语言中不可用。

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

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