该对象是一个Array或IEnumerable

Jun*_*nZe 0 .net c# reflection

我想知道是否有办法找到对象是数组还是IEnumerable,它比这更漂亮:

var arrayFoo = new int[] { 1, 2, 3 };

var testArray = IsArray(arrayFoo);
// return true
var testArray2 = IsIEnumerable(arrayFoo);
// return false

var listFoo = new List<int> { 1, 2, 3 };

var testList = IsArray(listFoo);
// return false
var testList2 = IsIEnumerable(listFoo);
// return true


private bool IsArray(object obj)
{
    Type arrayType = obj.GetType().GetElementType();
    return arrayType != null;
}

private bool IsIEnumerable(object obj)
{
    Type ienumerableType = obj.GetType().GetGenericArguments().FirstOrDefault();
    return ienumerableType != null;
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*nos 7

isC#中有一个关键字:

private bool IsArray(object obj)
{
    return obj is Array;
}

private bool IsIEnumerable(object obj)
{
    return obj is IEnumerable;
}
Run Code Online (Sandbox Code Playgroud)


Pre*_*cco 5

这有帮助吗?

"是"关键字

检查对象是否与给定类型兼容.

static void Test(object value)
{
    Class1 a;
    Class2 b;

    if (value is Class1)
    {
        Console.WriteLine("o is Class1");
        a = (Class1)o;
        // Do something with "a."
    } 
}
Run Code Online (Sandbox Code Playgroud)

"as"关键字

尝试将值转换为给定类型.如果强制转换失败,则返回null.

Class1 b = value as Class1;
if (b != null)
{
   // do something with b
}
Run Code Online (Sandbox Code Playgroud)

参考

"是"关键字

http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.110).aspx

"as"关键字

http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.110).aspx