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

kdb*_*man 2 c# generics emgucv

这是来自流行的EmguCV包的类签名.这是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()
Run Code Online (Sandbox Code Playgroud)

具体来说,注意

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

如何new()将类型参数约束为TDepth.NET整数类型?

Dav*_*d L 6

它没有.所有new()保证是具有约束的泛型类型(在这种情况下TDepth)必须提供无参数构造函数,并且根据文档它不是抽象的.

  • `TDepth`.我更新了我的答案以避免任何混淆:) (2认同)