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'.
感谢您的真棒解释。有没有什么办法来限制C#中的类型?我一直在阅读'CodeContracts',但似乎无法找到有关静态断言的任何文档。我希望他们可以工作。 – 2012-04-02 02:26:27
@NickStrupat在类型层次上,你几乎只限于'T:uint32','T:IEquatable','T:IEquatable '(这可能适合你)或者更广泛的东西。我还没有玩过代码合同,所以我不知道它们是如何工作的。 –
2012-04-02 02:30:26