c# - 如何将 T 限制为无符号积分?

标签 c# type-constraints

我一直在尝试以下方法

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 (由数据/操作确定的类型)。

unit32IUIntegral不相关:即使它们共享相同的结构

(无论如何,uint32 不符合 IEquatable<byte> 。)

如果类型需要与其自身相等,则可以通过引用类型限制中的类型来完成:

class Counter<T> where T : IEquatable<T> {
    T _value;
}

关于c# - 如何将 T 限制为无符号积分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970179/

相关文章:

haskell - 默认约束类型被忽略

c++ - 为什么编译器选择这个模板函数而不是重载的非模板函数?

c# - 处理 URL 中的媒体文件

c# - .NET SDK for Azure 中 Get-AzureRmResource 的 C# 等效项是什么?

c# - Java Web 服务使用 .Net

c# - 条件类型约束参数

.net - 了解 F# 静态成员约束(构造小于通用警告)

delphi - 为什么缺少可选参数会导致 "Incompatible types"错误

c# - 当特定属性更改时评估多重绑定(bind)

c# - 流畅的断言 : Using BeCloseTo on a collection of DateTime properties