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