C#模板用于int和float

Vir*_*721 2 c# generics templates

我有两个类,一个用于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" );
            Minimum = newMin;
        }

        public void SetMaximum( NumericType? newMax )
        {
            if( null != newMax && null != Minimum && (NumericType) newMax < (NumericType) Minimum )
                throw new Exception( "Maximum is below minimum" );
            Maximum = newMax;
        }

        public void SetDefault( NumericType? def )
        {
            Default = def;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于我不知道的原因,我收到以下错误:

error CS0019: Operator '>' cannot be applied to operands of type 'NumericType' and 'NumericType'
Run Code Online (Sandbox Code Playgroud)

我习惯使用C++模板,但不习惯C#模板,所以我在这里有点迷失.可能是什么原因?谢谢.

O. *_*per 5

如果不指定任何其他内容,NumericType则假定任何通用参数(例如您的)具有与之相同的功能System.Object.为什么?好吧,因为你的类的用户可能会传递System.ObjectNumericType参数.因此,无法保证传递给该泛型参数的类型支持>运算符,因此编译器不允许您使用它.

现在,你一定的限制NumericType,因为你需要传递给NumericType实现的任何类型IComparable<T>并且是一个结构.但是,这些限制都不能保证有>操作符,因此您仍然无法使用它.

在您的特定情况下,您可能希望使用该CompareTo方法,其传递给任何类型的可用性由您对类型实现的要求NumericType 保证IComparable<T>.但请注意,如果这对您造成问题,那么您的类也可以用于与数字无关的其他类型的负载.

通常,您在C#中无法正确回答查找允许用户提供数字类型的限制的特定任务,因为C#(或通常的CLI)中的数字类型不会从数字类型的公共基类继承.