如何在C#中创建Emgu CV Image泛型子类并解决CS0453错误?
问题描述
我正在使用C#的Emgu CV类库,想要创建Image类型的子类。我平时使用Image类的方式如下:
public Image<Gray, byte> grayImage = new Image<Gray, byte>(1920, 1080);
我编写的子类代码如下:
public class MyImage<T> where T : Emgu.CV.IColor { public MyImage() { Image<T, byte> ree = new Image<T, byte>(1920, 1080); } }
但编译时出现如下错误:
CS0453 The type 'T' must be a non-nullable value type in order to use it as parameter 'TColor' in the generic type or method 'Image<TColor, TDepth>'
已知IColor的定义如下:
public interface IColor { // // Summary: // The equivalent MCvScalar value MCvScalar MCvScalar { get; set; } // // Summary: // Get the dimension of the color type int Dimension { get; } }
请问如何通过将IColor设为非可空值类型,来创建该泛型类型的子类?
解决方案
问题出在泛型约束不匹配:EmguCV的Image<TColor, TDepth>对TColor的要求是非空值类型(struct)且实现IColor接口,你的MyImage<T>只约束了T实现IColor,没有限制它是值类型,所以编译报错。
只需修改MyImage的泛型约束,添加struct关键字即可:
public class MyImage<T> where T : struct, Emgu.CV.IColor { public MyImage() { Image<T, byte> ree = new Image<T, byte>(1920, 1080); } }
原因说明
EmguCV中所有内置的颜色类型(比如Gray、Bgr、Hsv等)都是值类型(struct),并且实现了IColor接口。Image<TColor, TDepth>的泛型定义里,TColor的约束就是struct, IColor,因此你的自定义泛型类必须继承同样的约束,才能合法创建Image<T, byte>的实例。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

