変数がスカラー型であることを確認する方法はありますか?
スカラー変数は、integer、float、double、string、または boolean を含み、配列オブジェクトを含まない変数です。
ありがとう
「スカラー」の意味にもよりますが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))) { }