简体   繁体   中英

How to implement a simple generic comparison in C#

I am just begining to explore the basic of using generics and would have thought i could implement this simple pattern to solve a typical problem in my daily use. I have spent days searching for a simple example. I can find examples for looking for .Equals, but not much past that. I want to be able to instantiate with things like:

Spec<double> voltageSpec;
Spec<int> cyclesSpec;
Spec<myClass> fishInTheOceanSpec;

then be able to :

bool isGood = voltageSpec.inSpec(5.0);
bool isGood cyclesSpec.inSpec(2);
bool isGood fishInTheOceanSpec.( new myClass(20));

My attempt is shown below.

/// <summary>
///  Generic object to hold a specification i.e min and max limits.
///  Implements a method to determin if a value is between limits.
/// </summary>
public class Spec<T> : IComparer<T> 
{
    public Spec()
    {
        Min = default(T);
        Max = default(T);
    }
    public T Min { get; set; }
    public T Max { get; set; }
    public bool inSpec(T Value) 
    {
        if ((Comparer<T>.Default.Compare(Value, this.Max) <= 0) &
            (Comparer<T>.Default.Compare(Value, this.Min) >= 0))
            return true;
        else 
            return false;
    }

    public int Compare(T x, T y)
    {
        if (x == y) return 0;
        if (x < y) return -1;
        if (x > y) return 1;
    }

    public Spec<T> Copy()
    {
        return (Spec<T>)this.MemberwiseClone();
    }
}

I would refactor as follows - make T be responsible to provide the comparison - this works already for primitive types, your custom classes just have to implement IComparable<T> :

public class Spec<T> where T : IComparable<T>
{
    public Spec()
    {
        Min = default(T);
        Max = default(T);
    }
    public T Min { get; set; }
    public T Max { get; set; }
    public bool inSpec(T Value)
    {
        if(Value.CompareTo(this.Max) <=0 &&
            Value.CompareTo(this.Min) >=0)
            return true;
        else
            return false;
    }

    public Spec<T> Copy()
    {
        return (Spec<T>)this.MemberwiseClone();
    }
}

Declare your class like this

public class Spec<T> : IComparer<T>
    where T : IComparable<T>
{
    .... 
}

Then you can apply CompareTo to T

public int Compare(T x, T y)
{
    return x.CompareTo(y);
}

Basic types like int , double or string do implement IComparable<T> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM