4

変数がスカラー型であることを確認する方法はありますか?

スカラー変数は、integer、float、double、string、または boolean を含み、配列オブジェクトを含まない変数です。

ありがとう

4

2 に答える 2

9

「スカラー」の意味にもよりますがType.IsPrimitive、良い一致のように聞こえます: trueboolean整数型、浮動小数点型、および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 に答える