简体   繁体   English

用`new()`约束类型参数是什么意思?

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

Here is a class signature from the popular EmguCV package. 这是流行的EmguCV包中的类签名。 It's the Image class - not all of it is important: 这是Image类-并非所有的类都很重要:

/// <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? new()如何将类型参数TDepth约束为.NET整数类型?

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 . 所有new()保证都是带有约束的泛型类型(在这种情况下为TDepth )必须提供无参数的构造函数,并且根据文档 ,它不是抽象的。

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

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