在一个封闭的结构中实现IComparable <>以便在通用函数中进行比较

问题描述:

我有一个C#.net 2.0 CF应用程序,用于验证对象的返回值。我无法修改此结构或返回它的函数。在一个封闭的结构中实现IComparable <>以便在通用函数中进行比较

/// This structure is returned by a function from the object under test 
public struct SomeType 
{ 
    int a; 
    int b; 
    char c; 
    string d; 

    public static SomeType Empty { get { return new SomeType(); } } 
} 

/// pretend this function is in the object under test 
static SomeType FunctionUnderTest() 
{ 
    return SomeType.Empty; 
} 

因为我可能必须为许多返回许多不同类型的函数执行此操作,所以我想使用通用比较函数。这是可以修改的。

static bool Compare<T>(ValidationTypes ValidateCond, 
    T ActualValue, 
    T ExpectedValue) where T : System.IComparable<T> 
{ 
    switch (ValidateCond) 
    { 
     case ValidationTypes.Equal: 
      return ActualValue.CompareTo(ExpectedValue) == 0; 
     case ValidationTypes.NotEqual: 
      return ActualValue.CompareTo(ExpectedValue) != 0; 
     case ValidationTypes.LessThan: 
      return ActualValue.CompareTo(ExpectedValue) < 0; 
     // more interesting things... 
    } 
    return false; 
} 

但是,这意味着从结构的作用下测试返回必须实现System.IComparable <>接口。我想这样的事情,这是自结构密封显然是行不通的,但应该给你的东西我在寻找一个想法:

/// our test creates a custom version of this structure that derives from 
/// the System.IComparable<> interface. 
public class SomeTypeUnderTest : SomeType, System.IComparable<SomeTypeUnderTest> 
{ 
    #region IComparable<SomeTypeUnderTest> Members 

    public int CompareTo(SomeTypeUnderTest other) 
    { 
     // insert some comparison function between object and this 

     return 0; 
    } 

    #endregion 
} 

因此,我可以用这样的:

bool res = Type<int>(ValidationTypes.Equal, 1, 2); 

bool res2 = Type<SomeTypeUnderTest>(ValidationTypes.Equal, 
    new FunctionUnderTest(), 
    new SomeType.Empty); 

请让我知道是否有人有任何建议如何正确地做到这一点。

感谢, PaulH

你有没有想过实现IComparer<T>接口,为您的结构?

该类型本身不会执行比较。当你想比较两个值时,你可以使用IComparer <T>实例。

int result1 = Comparer<int>.Default.Compare(1, 2); 
         // the Default comparer defaults 
         // to IComparable<T>.CompareTo 

int result2 = new SomeTypeComparer().Compare(FuncUnderTest(), SomeType.Empty); 
+0

完美。谢谢 – PaulH 2010-10-07 19:02:23

我建议引入到静态布尔一个新的参数进行比较(),它是类型比较的(委托INT比较(T A,T B))或IComparer的,可以调用它,而不是value.CompareTo