How to define generic type limit to primitive types?

后端 未结 5 1249
清歌不尽
清歌不尽 2020-12-03 00:13

I have the following method with generic type:

T GetValue();

I would like to limit T to primitive types such as int, string, float

相关标签:
5条回答
  • 2020-12-03 00:54

    Here's what you're looking for:

    T GetObject<T>() where T : struct;
    
    0 讨论(0)
  • 2020-12-03 00:55

    There is no generic constraint that matches that set of things cleanly. What is it that you actually want to do? For example, you can hack around it with runtime checks, such as a static ctor (for generic types - not so easy for generic methods)...

    However; most times I see this, it is because people want one of:

    • to be able to check items for equality: in which case use EqualityComparer<T>.Default
    • to be able to compare/sort items: in which case use Comparer<T>.Default
    • to be able to perform arithmetic: in which case use MiscUtil's support for generic operators
    0 讨论(0)
  • 2020-12-03 01:00

    What are you actually trying to do in the method? It could be that you actually need C to implement IComparable, or someother interface. In which case you want something like

    T GetObject<T> where T: IComparable
    
    0 讨论(0)
  • 2020-12-03 01:04

    Actually this does the job to certain extend:

    public T Object<T>() where T :
       struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
    

    To limit to numeric types you can get some useful hints of the following samples defined for the ValueType class

    0 讨论(0)
  • 2020-12-03 01:09

    You can use this to limit it to value types:

    where C: struct
    

    You also mention string. Unfortunately, strings won't be allowed as they are not value types.

    0 讨论(0)
提交回复
热议问题