开发者

Implementing IComparable<> in a sealed struct for comparison in a generic function

I have a C# .net 2.0 CF application where I'm validating the return value from an object. I cannot modify this structure or t开发者_如何学Pythonhe function that returns it.

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

Since I may have to do this for many functions returning many different types, I wanted to use a generic comparison function. This is open to modification.

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

But, that means the structure returned from the function under test has to implement the System.IComparable<> interface. I was thinking something like this, which obviously won't work since structs are sealed, but should give you an idea of what I'm looking for:

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

Thus, I could use it like this:

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

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

Please, let me know if anybody has any suggestions on how to properly do this.


Have you thought about implementing the IComparer<T> interface for your structure?

The type wouldn't implement comparisons itself. When you want to compare two values, you would use the IComparer<T> instance instead.

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

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


I would propose to introduce a new parameter to static bool Compare(), which is of type Comparison (delegate int Comparison(T a, T b)) or IComparer, can call it rather than value.CompareTo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜