简体   繁体   中英

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#

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

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