简体   繁体   中英

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. 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() )
  • 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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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