开发者

Constraints on Type parameters [duplicate]

This question already has answers here: Is there a constraint that restricts my generic method to numeric types? (24 answers)开发者_JAVA技巧 Closed 8 years ago.

Is there a way to constraint a generic type to only integral type?

In example, if I have a method

T[] sort<T>(T[] data) where : T ... {}

what would I put as constraint if I wanted to ensure the parameter will be some sort of integral type?

I have tryed looking at MSDN however it does not seem to mention anything about constraining and primitive types.

Thank you for your help.


Nope. I asked this question before with VB.Net.

Generic Classes (T) - Specifying from a Range of Types VB.Net

As quoted from the page above:
Also, you mentioned constraining to numerics, but I don't think you can constrain to just that. You can however constrain to just primitive types (on the stack) and not allow objects (on the heap) by doing this: Public Structure Statistic(Of t As {Structure, IComparable}).


The same technique -- constraining generic types to be (in C#) struct and IComparable, came up as an answer to detecting boxed values for performance.

How to test whether a value is boxed in C# / .NET?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜