将泛型类型参数仅限制为数字类型

时间:2017-06-14 23:27:06

标签: c# class generics inheritance types

我正在上课class numToBin <T>,我需要确保T是一个数值(例如,Float, Double, Int, Long, UInt, Ulong, byte, short, BigInteger)。我看过很多帖子都在问同样的问题,但他们都已经有几年了。

我的问题是:语言是否有任何更改才能允许它?  目前我有:

class numToBin <T>
    where T : struct, IEquatable<T>, IFormattable, IComparable, IComparable<T>

但像T a = 0;这样的东西不起作用。

2 个答案:

答案 0 :(得分:1)

不,“数字”类型仍然没有泛型类型约束。

要明确获取T a = 0,您可以使用T a = default(T)。所有数字类型的默认值均为0.

答案 1 :(得分:0)

在类的构造函数中,执行类型检查以匹配适用的类型。如果失败则抛出InvalidCastException或InvalidArgumentException。

Type t = typeof(T);
bool good = (t == typeof(int)) || (t == typeof(long))|| //...
if(!good)
 //die
相关问题