通用接口问题
本文关键字:问题 接口 | 更新日期: 2023-09-27 17:56:53
所以我的问题来了:
我有界面:
public interface ICell<Feature>
where Feature: struct, IComparable<ICell<Feature>>
{
List<ICell<Feature>> Window { get; set; }
Feature GenusFeature { get; set; }
Double VitalityRatio { get; set; }
String PopulationMarker { get; set; }
Boolean Captured { get; set; }
}
并希望以这种方式实现ISubstratum
接口:
public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct
{
ICell<T> this[Int32 i, Int32 j] { get; set; }
}
但是编译器说:
The type 'T' cannot be used as type parameter 'Feature' in the generic type or method 'Colorizer.Core.ICell<Feature>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<Colorizer.Core.ICell<T>>'.
在某些可能的ISubstratum
实现中,我计划将位图作为 K &&ICell(扩展像素信息)作为 T 传递。
如何解决这个问题?
谢谢!
基本上,
你必须对 T 有一个额外的约束:
where T : struct, IComparable<ICell<T>>
那么它应该可以正常工作。这是满足ICell<Feature>
中对Feature
的相同约束所必需的。
我还建议您将类型参数重命名Feature
为 TFeature
,以使其更明显地成为类型参数。
因为您对 ISubstratum
接口的T
泛型类型参数的约束不够具体。它应该是:
where T : struct, IComparable<ICell<Feature>>
您需要要求 T 实现 ICell 类型定义定义的IComparable<ICell<T>>
。
是因为您在ISubstratum<K,T>
中的T
仅限于结构,而ICell<T>
中的T
也需要IComparable<ICell<T>>
?如果你在哪里添加那个附加物,它有效吗?
public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct, IComparable<ICell<T>>
{
ICell<T> this[Int32 i, Int32 j] { get; set; }
}
?
public interface ISubstratum<K,T> : IDisposable
where K : IDisposable
where T : struct, IComparable<ICell<Feature>>
{
ICell<T> this[Int32 i, Int32 j] { get; set; }
}