如何比较泛型类型的值?
我把它减少到最小的样本:
public class Foo<T> where T : IComparable
{
private T _minimumValue = default(T);
public bool IsInRange(T value)
{
return (value >= _minimumValue); // <-- Error here
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
运算符'> ='不能应用于'T'和'T'类型的操作数.
到底怎么回事!?T已被约束到IComparable,甚至它限制值类型(的时候where T: struct),我们仍然不能将任何运营商<,>,<=,>=,==或!=.(我知道,涉及到解决方法Equals()的存在==和!=,但它并不能帮助对于关系运算符).
那么,有两个问题:
IComparable?它不是以某种方式打败了通用约束的整个目的吗?(我意识到已经有一些问题与这个看似简单的问题有关 - 但没有一个线程能给出详尽或可行的答案,所以在这里.)
概要:我需要使用两个通用的C#对象,如果它们是数字,则使用小于或大于比较来比较它们.
问题:我无法弄清楚如何让我的类实现IComparable,如本文所述:必须实现一个小于和大于操作的泛型.如果这不是正确的路径,那么我也需要知道.
背景:我已经实现了在更复杂的自定义验证器中找到的RequiredIf ValidationAttribute,但除了等于比较之外还需要>和<选项.
代码(取自更复杂的自定义验证器,页面下三分之一):
private bool IsRequired(object actualPropertyValue)
{
switch (Comparison)
{
case Comparison.IsLessThan:
case Comparison.IsLessThanOrEqualTo:
case Comparison.IsGreaterThan:
case Comparison.IsGreaterThanOrEqualTo:
if (!Value.IsNumber())
{
throw new Exception("The selected comparison option is only applicable to numeric values");
}
break;
}
switch (Comparison)
{
case Comparison.IsNotEqualTo:
return actualPropertyValue == null || !actualPropertyValue.Equals(Value);
case Comparison.IsEqualTo:
return actualPropertyValue != null && actualPropertyValue.Equals(Value);
case Comparison.IsGreaterThan:
// THIS LINE FAILS BECAUSE actualPropertyValue DOESN'T IMPLEMENT IComparable
return …Run Code Online (Sandbox Code Playgroud) 我有两个类,一个用于float,一个用于int.他们的代码是完全相同的,我想编写一个兼容int和float的模板类,以便不使用不同的类型复制这些代码.
这是我的班级:
namespace XXX.Schema
{
public abstract class NumericPropDef< NumericType > : PropDef
where NumericType : struct, IComparable< NumericType >
{
public NumericType? Minimum { get; protected set; }
public NumericType? Maximum { get; protected set; }
public NumericType? Default { get; protected set; }
public NumericPropDef() : base() { }
public void SetMinimum( NumericType? newMin )
{
if( null != newMin && null != Maximum && (NumericType) newMin > (NumericType) Maximum )
throw new Exception( "Minimum exceeds maximum" ); …Run Code Online (Sandbox Code Playgroud) 我想对整数或双精度数组进行排序.为此,我想使用一种方法.我的问题是我不知道如何传递一个未知类型的数组作为参数.我试过这个
public static void BubbleSort<T>(T[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length - 1; j++)
{
//Can't use greater than because of T
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我不能使用大于运算符,因为数组也可以是字符串数组.