如何检查变量是标量
本文关键字:变量 标量 检查 何检查 | 更新日期: 2023-09-27 18:34:39
有没有办法检查变量是标量类型?
标量变量是那些包含整数、浮点数、双精度、字符串或布尔值但不包含数组对象的变量
谢谢
这取决于
你所说的"标量"是什么意思,但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
}
我不确定这是否总是有效,但它可能足以满足您的需求:
if (!(YourVarHere is System.Collections.IEnumerable)) { }
或者,要检查Type
:
if(!typeof(YourTypeHere).GetInterfaces().Contains(typeof(System.Collections.IEnumerable))) { }