4

有没有一种方法可以检查变量是否为标量类型?

标量变量是那些包含整数、浮点数、双精度、字符串或布尔值但不包含数组对象的变量

谢谢

4

2 回答 2

9

这取决于您所说的“标量”是什么意思,但Type.IsPrimitive听起来很合适:它true适用于boolean、整数类型、浮点类型和char.

你可以使用它

var x = /* whatever */
if (x.GetType().IsPrimitive) {
    // ...
}

对于更精细的方法,您可以Type.GetTypeCode改用:

switch (x.GetType().GetTypeCode()) {
    // put all TypeCodes that you consider scalars here:
    case TypeCode.Boolean:
    case TypeCode.Int16:
    case TypeCode.Int32:
    case TypeCode.Int64:
    case TypeCode.String:
        // scalar type
        break;
    default:
        // not a scalar type
}
于 2013-10-10T09:23:27.750 回答
2

我不确定这是否会一直有效,但这可能足以满足您的需求:

if (!(YourVarHere is System.Collections.IEnumerable)) { }

或者,用于检查Type

if(!typeof(YourTypeHere).GetInterfaces().Contains(typeof(System.Collections.IEnumerable))) { }
于 2013-10-10T09:25:02.263 回答