我有两个类,一个用于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;
}
}
}
但是由于我不知道的原因,出现以下错误:
error CS0019: Operator '>' cannot be applied to operands of type 'NumericType' and 'NumericType'
我习惯了C ++模板,但不习惯C#模板,因此在这里我有点迷路。这可能是什么原因?谢谢你。
在不指定其他任何内容的情况下,任何通用参数(例如your NumericType
)都假定具有与相同的功能System.Object
。为什么?好吧,因为您的类的用户可能会传递System.Object
给NumericType
参数。因此,不能保证传递给该通用参数的类型支持>
运算符,因此编译器不允许您使用它。
现在,您已经有所限制NumericType
,因为您需要传递用于NumericType
实现的任何类型,IComparable<T>
并且必须是结构。但是,这些限制都不能保证有>
操作员,因此您仍然不能使用它。
在您的特定情况下,你可能想使用的CompareTo
方法,在任何类型的市场供应传递给NumericType
被你的要求,即实现类型保证IComparable<T>
。但是请注意,像这样,如果给您带来了问题,您的类也可以用于与数字无关的其他类型的负载。
通常,在C#中无法正确回答您寻找限制让用户提供数字类型的限制的特定要求,因为C#(或一般的CLI)中的数字类型不会从数字类型的通用基类继承。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句