如何实现一个简单的泛型比较在C# [英] 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;
则可以:
bool isGood = voltageSpec.inSpec(5.0);
bool isGood cyclesSpec.inSpec(2);
bool isGood fishInTheOceanSpec.( new myClass(20));
我的尝试如下所示。
/// <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将重构如下 - make T
负责提供比较 - 这已经为原始类型,您的自定义类只需要实现 IComparable< T> ;
:
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();
}
}
这篇关于如何实现一个简单的泛型比较在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!