gpt4 book ai didi

int 和 float 的 C# 模板

转载 作者:行者123 更新时间:2023-12-03 20:30:26 25 4
gpt4 key购买 nike

我有两个类,一个用于 float,一个用于 int。他们的代码完全相同,我想编写一个与 int 和 float 兼容的模板类​​,以免仅使用不同的类型复制此代码。

这是我的类(class):

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# 模板,所以我在这里有点迷失。这可能是什么原因?谢谢。

最佳答案

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

现在,您一些限制NumericType ,因为您需要将任何类型传递给 NumericType实现 IComparable<T> 并且是一个结构体。然而,这些限制都不能保证有 >运算符,因此您仍然无法使用它。

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

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

关于int 和 float 的 C# 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com