C#int和float的模板

C#int和float的模板,c#,templates,generics,C#,Templates,Generics,我有两个类,一个用于float,另一个用于int。它们的代码完全相同,我想编写一个与int和float兼容的模板类,以避免用不同的类型复制此代码 这是我的班级: namespace XXX.Schema { public abstract class NumericPropDef< NumericType > : PropDef where NumericType : struct, IComparable< NumericType > {

我有两个类,一个用于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;
        }
    }
}

我习惯了C++模板,但不习惯C++模板,所以我在这里有点迷茫。原因可能是什么?谢谢。

在不指定任何其他内容的情况下,假定任何通用参数(如
NumericType
)都具有与相同的功能。为什么?因为类的用户可能会将
System.Object
传递给
NumericType
参数。因此,不能保证传递给该泛型参数的类型支持
运算符,因此编译器不允许您使用它

现在,您对
NumericType
进行了一些限制,因为您需要传递给
NumericType
的任何类型都实现并且是一个结构。但是,这些限制都不能保证存在
运算符,因此您仍然无法使用它

在您的特定情况下,您可能希望使用,其在传递给
NumericType
的任何类型上的可用性由您的要求保证,即该类型实现
IComparable
。但是,请注意,像这样,您的类也可以用于与数字无关的其他类型的加载,如果这会给您带来问题的话


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

查看第一个答案:默认值为
NumericType?
(可以为空)这与
NumericType
…不同,解决此问题的方法是使用
Comparer.Default.Compare
方法谢谢您的帮助。我认为IComparable确保了比较运算符的实现。@Virus721:如果是这样,相应的运算符将列在中的运算符部分。@Lucastrezesniewski:这与我在回答中提到的
方法相比有什么优势吗?@O.R.Mapper我能想到的唯一优势是不必检查
null
(这无论如何都不适用于结构)-在您将
比较添加到
部分之前,我写了这条评论。
error CS0019: Operator '>' cannot be applied to operands of type 'NumericType' and 'NumericType'