2017-01-08 35 views
-3

在調試模式下,我盤旋在我的變量,它表明,它是{對象[0]}如何檢查對象是否爲object [0]?

enter image description here

然而,這個if語句永遠不會得到觸發。

如何檢查此對象[0]類型?

+0

'object [0]'可能意味着它的空集合很難說。這個對象從哪裏來? –

+0

在這種情況下element.GetType()。FullName返回什麼? – RQDQ

+0

你如果陳述似乎沒有多大意義。您能否更新答案並解釋您爲什麼使用此檢查? – Soviut

回答

2

要檢查的objectobject[],你的支票element is object[]已經是正確的。

要檢查object[]是否爲空,調用Any()已經正確,但一定要在正確的實例上調用它。避免使用擴展方法,因爲它沒有達到你期望的效果。

if (element is object[] && !((object[]) element).Any()) 
    // element is an empty array of objects 

測試:

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace Tester { 
    static class Program { 
     static void Test(string name, object element) { 
      Console.Write($"{name}: "); 
      Console.WriteLine(element is object[] && !((object[])element).Any()); 
     } 

     static void Main(string[] args) { 
      Test("new object()",  new object());  // false 
      Test("new { }",   new { });   // false 
      Test("new object[0]",  new object[0]);  // true 
      Test("new object[1]",  new object[1]);  // false 

      Test("new List<object>()", new List<object>()); // false 
      // Note: object[] o = new List<object>(); wouldn't be allowed. 

      Test("new string[0]",  new string[0]);  // true 
      // Note: object[] o = new string[0]; would be allowed. 

      Test("new int[0]",   new int[0]);   // false 
      // Note: object[] o = new int[0]; wouldn't be allowed. 
     } 
    } 
} 

這包括一些測試情況下,可能是一個跡象,你正在試圖做的檢查是不是一個好主意,但它也表明,它可以給出精確結果。

1

沒有object[0]類型。它告訴你的是它是一個空對象的數組。

1

你試過:

var test = element as IEnumerable; 

If (test != null && test.Any()) 
{ 
+0

我有,它看起來像是元素是一個Guid那麼它是一個IEnumerable –

+0

@l - '''''' - - '''''''''''''不,['Guid'](https://msdn.microsoft.com/en-us/library/system.guid(v = vs.110).aspx)不實現IEnumerable。也許你正在查看一個['string'](https://msdn.microsoft.com/en-us/library/system.string(v = vs.110).aspx),這恰好代表Guid? 'string'實現'IEnumerable'。 – hvd

+0

正確!這是一個字符串。 –