Best way to test if a generic type is a string? (C#)

后端 未结 6 1158
不知归路
不知归路 2020-12-13 01:09

I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type

6条回答
  •  执笔经年
    2020-12-13 01:47

    You can use the TypeCode enumeration. Call the GetTypeCode method on classes that implement the IConvertible interface to obtain the type code for an instance of that class. IConvertible is implemented by Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char, and String, so you can check for primitive types using this. More info on "Generic Type Checking".

提交回复
热议问题