Implementing a common interface with type restrictions

I have a Visual Studio 2008 C # 2.0 CF project where I implement a common interface, IComparison . The IComparison.Compare method can be called to perform any type of comparison that is valid for the specified objects, so I do not want to impose a type restriction on it.

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

However, the implementation may be more specific. In this case, I would like to say that the parameter specified by GreaterThan.Compare can be compared with EXPECTED_PARAM specified in the constructor via 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; } } 

Unfortunately this gives me an error:

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

What do I need to do to be able to perform arbitrary comparisons of EXPECTED_PARAM objects with RETURNED_PARAM objects?

Thanks PaulH

+4
source share
2 answers

How about this?

  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; } } 
+2
source

Your inheritance hierarchy is a problem. GreaterThan inherits from IComparison<EXPECTED_PARAM> , which means that you tell the compiler that it implements Compare<EXPECTED_PARAM> , but you want it to implement Compare<RETURNED_PARAM> . You can abandon the general restriction on your interface:

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

All Articles