How to implement a simple generic comparison in C#

心已入冬 提交于 2019-12-11 12:25:58

问题


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

回答1:


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



回答2:


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>.



来源:https://stackoverflow.com/questions/9624318/how-to-implement-a-simple-generic-comparison-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!