我一直在尝试以下方法
interface IUIntegral : IEquatable<Byte>, IEquatable<UInt16>, IEquatable<UInt32>, IEquatable<UInt64> { }
class Counter<T> where T : IUIntegral {
T _value;
}
使用此调用代码
Counter<UInt32> foo = null;
但是我收到这个编译器错误
Error 1 The type 'uint' cannot be used as type parameter 'T' in the generic type or method 'Test.Counter<T>'. There is no boxing conversion from 'uint' to 'Test.IUIntegral'.
最佳答案
tldr;这种方法行不通。
C# 使用 nominative type system (类型由名称确定)并且不是 structural type system (由数据/操作确定的类型)。
unit32
和IUIntegral
不相关:即使它们共享相同的结构。
(无论如何,uint32
不符合 IEquatable<byte>
。)
如果类型需要与其自身相等,则可以通过引用类型限制中的类型来完成:
class Counter<T> where T : IEquatable<T> {
T _value;
}
关于c# - 如何将 T 限制为无符号积分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970179/