OpenCVSharp.GaussianBlur
过滤器,但我要让它通用,以便可以插入我创建的任何自定义过滤器)。我在C#泛型方面遇到了一些困难,智能感知显示:
Intellisense建议更改以下行:无法从'GaussianBlur'转换为'IFilter'
filters.Enqueue(filter);
通过对接口进行强制类型转换:
filters.Enqueue((IFilter<IFilterParams>)filter);
然而,我的问题是:为什么需要进行强制类型转换,当具体类实现了接口并且按照泛型定义需要它,或者我是否误解了如何使用泛型声明类。目前的实现代码如下:
public class FilterTest
{
private FilterCollection filters = new FilterCollection();
/* ... other irrelevant code ... */
public void ApplyFilters(ref Mat buffer)
{
var filter = new GaussianBlur(new GaussianBlurParams { KernelSize = new Size(6, 6) });
filters.Enqueue((IFilter<IFilterParams>)filter);
filters.Apply(ref buffer);
}
}
我正在为FilterCollection扩展Queue<>类:
public class FilterCollection : Queue<IFilter<IFilterParams>>
{
public void Apply(ref Mat buffer)
{
while (Count > 0)
Dequeue().Apply(ref buffer);
}
}
IFilter和IFilterParams的接口如下:
public interface IFilter<T> where T : IFilterParams
{
void Apply(ref Mat buffer);
}
public interface IFilterParams { }
接下来是示例过滤器的实现(在这种情况下更多是一个包装器):
public class GaussianBlurParams : IFilterParams
{
public Size KernelSize = new Size(5, 5);
public double SigmaX = default(double);
public double SigmaY = default(double);
public BorderTypes BorderType = BorderTypes.Default;
}
public class GaussianBlur : IFilter<GaussianBlurParams>
{
private GaussianBlurParams p;
public GaussianBlur(GaussianBlurParams filterParams)
{
this.p = filterParams;
}
public void Apply(ref Mat buffer)
{
Cv2.GaussianBlur(buffer, buffer, p.KernelSize, p.SigmaX, p.SigmaY, p.BorderType);
}
}
所以,假设:
GaussianBlur
实现了IFilter<GaussianBlurParams>
- 并且
IFilter<T> where T : IFilterParams
- 而且
GaussianBlurParams
实现了IFilterParams