2012-04-02 59 views
2

我一直在尝试以下如何将T限制为无符号整数?

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'. 

回答

5

tldr;这种方法不起作用。

C#使用nominative type system(类型是由名字确定的)和未一个structural type system(类型由数据/操作来确定)。

unit32IUIntegral是没有关系的:即使它们共享相同的结构

如果一个类型必须与Equatable这本身可以参照类型的类型限制来完成(他们不反正uint32不符合IEquatable<byte>。)

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

感谢您的真棒解释。有没有什么办法来限制C#中的类型?我一直在阅读'CodeContracts',但似乎无法找到有关静态断言的任何文档。我希望他们可以工作。 – 2012-04-02 02:26:27

+1

@NickStrupat在类型层次上,你几乎只限于'T:uint32','T:IEquatable ','T:IEquatable '(这可能适合你)或者更广泛的东西。我还没有玩过代码合同,所以我不知道它们是如何工作的。 – 2012-04-02 02:30:26

相关问题