通用接口问题

时间:2011-05-16 21:57:29

标签: c# interface generics

所以这是我的问题:

我有界面:

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&amp;&amp; ICell(扩展像素信息)为T。

如何解决这个问题?

谢谢!

5 个答案:

答案 0 :(得分:6)

基本上你必须对T:

有额外的限制
where T : struct, IComparable<ICell<T>>

然后它应该工作正常。这需要满足FeatureICell<Feature>的相同约束。

我还建议您将类型参数Feature重命名为TFeature,使其更明显为类型参数。

答案 1 :(得分:1)

因为您对T接口的ISubstratum泛型类型参数的约束不够具体。它应该是:

where T : struct, IComparable<ICell<Feature>>

答案 2 :(得分:1)

您需要要求T实现ICell类型定义所定义的IComparable<ICell<T>>

答案 3 :(得分:1)

是否因为T中的ISubstratum<K,T>仅限于结构,而T中的ICell<T>也需要IComparable<ICell<T>>?如果你在那里添加additi,它有用吗?

public interface ISubstratum<K,T> : IDisposable 
where K : IDisposable
where T : struct, IComparable<ICell<T>>
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}

答案 4 :(得分:1)

public interface ISubstratum<K,T> : IDisposable 
where K : IDisposable
where T : struct, IComparable<ICell<Feature>>
{
    ICell<T> this[Int32 i, Int32 j] { get; set; }
}