c# – 实现具有类型约束的通用接口

我有一个Visual Studio 2008 C#2.0 CF项目,我正在实现一个通用接口IComparison.可以调用IComparison.Compare方法来执行对指定对象有效的任何类型的比较,因此我不想对其设置类型约束.

public interface IComparison<EXPECTED_PARAM>
{
    Result Compare<RETURNED_PARAM>(RETURNED_PARAM returned);
}

但是,实施可以更具体.在这种情况下,我想说可以将给予GreaterThan.Compare的参数与构造函数中通过System.IComparable给出的EXPECTED_PARAM进行比较.

public class GreaterThan<EXPECTED_PARAM> : IComparison<EXPECTED_PARAM>
{
    private EXPECTED_PARAM expected_;

    public GreaterThan(EXPECTED_PARAM expected)
    {
        expected_ = expected;
    }

    public Result Compare<RETURNED_PARAM>(RETURNED_PARAM returned) 
        where RETURNED_PARAM : IComparable< EXPECTED_PARAM >
    {
        return ((returned == null && expected_ == null) ||
                (returned != null && returned.CompareTo( expected_ ) > 0)) ?
               Result.Fail : Result.Pass;
    }
}

不幸的是,这给了我错误:

error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly

为了能够使用RETURNED_PARAM对象执行EXPECTED_PARAM对象的任意比较,我需要做什么?

谢谢,
PaulH

最佳答案 这个怎么样?

    public interface IComparison<EXPECTED_PARAM, RETURNED_PARAM>
{
    Result Compare(RETURNED_PARAM returned);
}

public class GreaterThan<EXPECTED_PARAM, RETURNED_PARAM> : IComparison<EXPECTED_PARAM, RETURNED_PARAM> where RETURNED_PARAM : IComparable<EXPECTED_PARAM>
{
    private EXPECTED_PARAM expected_;      
    public GreaterThan(EXPECTED_PARAM expected)     
    {         expected_ = expected;     }      

    public Result Compare(RETURNED_PARAM returned)          
    {
        return ((returned == null && expected_ == null) || 
            (returned != null && returned.CompareTo( expected_ ) > 0)) ?                
            Result.Fail : Result.Pass;
    }
} 
点赞