简体   繁体   中英

What does it mean to constrain a type parameter with `new()`?

Here is a class signature from the popular EmguCV package. It's the Image class - not all of it is important:

/// <summary>
/// An Image is a wrapper to IplImage of OpenCV. 
/// </summary>
/// <typeparam name="TColor">Color type of this image (either Gray, Bgr, Bgra, Hsv, Hls, Lab, Luv, Xyz, Ycc, Rgb or Rbga)</typeparam>
/// <typeparam name="TDepth">Depth of this image (either Byte, SByte, Single, double, UInt16, Int16 or Int32)</typeparam>
public partial class Image<TColor, TDepth>
  : CvArray<TDepth>, IImage, IEquatable<Image<TColor, TDepth>>
  where TColor : struct, IColor
  where TDepth : new()

Specifically, note

  ...
  where TDepth : new()  // <-- either Byte, SByte, Single, double, UInt16, Int16 or Int32

How does new() constrain the type parameter TDepth to the .NET integral types?

It doesn't. All new() guarantees is that the generic type with the constraint (in this case TDepth ) MUST provide a parameterless constructor and that it is not abstract, per the documentation .

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