使用.Net,如何确定类型是否为数值ValueType?
时间:2020-03-06 14:38:01 来源:igfitidea点击:
但这是一个例子:
Dim desiredType as Type if IsNumeric(desiredType) then ...
编辑:我只知道类型,而不是作为字符串的值。
好的,很不幸,我不得不循环遍历TypeCode。
但这是一种不错的方法:
if ((desiredType.IsArray)) return 0; switch (Type.GetTypeCode(desiredType)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; } ;return 0;
解决方案
我们可以使用Type.GetTypeCode()方法找出变量是否为数字:
TypeCode typeCode = Type.GetTypeCode(desiredType); if (typeCode == TypeCode.Double || typeCode == TypeCode.Integer || ...) return true;
我们需要在" ..."部分中完成所有可用的数字类型;)
此处有更多详细信息:TypeCode枚举
很棒的文章在这里探索C#的IsNumeric。
选项1:
引用Microsoft.VisualBasic.dll,然后执行以下操作:
if (Microsoft.VisualBasic.Information.IsNumeric("5")) { //Do Something }
选项2:
public static bool Isumeric (object Expression) { bool f; ufloat64 a; long l; IConvertible iConvertible = null; if ( ((Expression is IConvertible))) { iConvertible = (IConvertible) Expression; } if (iConvertible == null) { if ( ((Expression is char[]))) { Expression = new String ((char[]) Expression); goto IL_002d; // hopefully inserted by optimizer } return 0; } IL_002d: TypeCode typeCode = iConvertible.GetTypeCode (); if ((typeCode == 18) || (typeCode == 4)) { string str = iConvertible.ToString (null); try { if ( (StringType.IsHexOrOctValue (str, l))) { f = true; return f; } } catch (Exception ) { f = false; return f; }; return DoubleType.TryParse (str, a); } return Utils.IsNumericTypeCode (typeCode); } internal static bool IsNumericType (Type typ) { bool f; TypeCode typeCode; if ( (typ.IsArray)) { return 0; } switch (Type.GetTypeCode (typ)) { case 3: case 6: case 7: case 9: case 11: case 13: case 14: case 15: return 1; }; return 0; }
使用Type.IsValueType()和TryParse():
public bool IsInteger(Type t) { int i; return t.IsValueType && int.TryParse(t.ToString(), out i); }
''// Return true if a type is a numeric type. Private Function IsNumericType(ByVal this As Type) As Boolean ''// All the numeric types have bits 11xx set whereas non numeric do not. ''// That is if you include char type which is 4(decimal) = 100(binary). If this.IsArray Then Return False If (Type.GetTypeCode(this) And &HC) > 0 Then Return True Return False End Function