2013-07-25 42 views
0

我不知道是否有辦法找到,如果對象是一個數組或IEnumerable的,它是比這更漂亮:的對象是一個數組或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; 
} 
+1

這個問題存在一個基本問題:數組* *是* IEnumerable。 – StriplingWarrior

+0

您的'IsEnumerable'只檢查泛型類型。 'MyAbstractClass '將返回true。 –

+0

您'IsIEnumerable'不測試一個項目是否爲'IEnumerable'。它用至少一個泛型參數來測試該類型是否是泛型類型。 – shf301

回答

7

有一個is C#中的關鍵字:

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

private bool IsIEnumerable(object obj) 
{ 
    return obj is IEnumerable; 
} 
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." 
    } 
} 

「爲」 關鍵字

嘗試的值轉換爲給定類型。如果轉換失敗,則返回null。

Class1 b = value as Class1; 
if (b != null) 
{ 
    // do something with b 
} 

參考

「是」 關鍵字

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

「爲」 關鍵字

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

相關問題