Skip to main content
 首页 » 编程设计

c#之在密封结构中实现 IComparable> 以便在通用函数中进行比较

2024年02月24日27三少

我有一个 C# .net 2.0 CF 应用程序,我在其中验证对象的返回值。我无法修改此结构或返回它的函数。

/// 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<> 接口(interface)。我在想这样的事情,这显然是行不通的,因为结构是密封的,但应该让您了解我在寻找什么:

/// 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); 

如果有人对如何正确执行此操作有任何建议,请告诉我。

请您参考如下方法:

您是否考虑过实现 IComparer<T>结构的接口(interface)?

该类型本身不会实现比较。当您想要比较两个值时,您可以改用 IComparer 实例。

int result1 = Comparer<int>.Default.Compare(1, 2); 
                         // the Default comparer defaults 
                         // to IComparable<T>.CompareTo 
 
int result2 = new SomeTypeComparer().Compare(FuncUnderTest(), SomeType.Empty);