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

时间:2011-06-21 16:14:05

标签: c# generics c#-2.0 type-constraints

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

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

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

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

我需要做些什么才能使用EXPECTED_PARAM个对象执行RETURNED_PARAM个对象的任意比较?

谢谢, PaulH

2 个答案:

答案 0 :(得分:2)

这个怎么样?

    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;
    }
} 

答案 1 :(得分:0)

您的继承层次结构是个问题。 GreaterThan继承自IComparison<EXPECTED_PARAM>,这意味着您告诉编译器它实现了Compare<EXPECTED_PARAM>,但您希望它实现Compare<RETURNED_PARAM>。您可以在界面上删除通用约束:

public interface IComparison
{
    Result Compare<RETURNED_PARAM>(RETURNED_PARAM returned)
    where RETURNED_PARAM : IComparable;
}

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

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

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