簡體   English   中英

C#訪問System.Object []中的數據

[英]C# Accessing data in System.Object[]

我正在用C#編寫代碼,並且有一個包含大量數據的字典。 成員之一是“孩子”,但是當我嘗試寫出它的值時,我得到:System.Object []

我知道孩子包含數據,可能是嵌套數據,但是我不確定它是否是列表,字典,數組等。

如何寫出“兒童”中的所有數據?

任何實例化的.NET類型對“ ToString()”的默認響應是寫出完全限定的類型名稱。

System.Object []意味着您有一個數組,其中每個元素的類型均為“ Object”。 此“框”可以包含任何內容,因為.NET中的每種類型都源自Object。 以下可能會告訴您根據實例化類型,數組真正包含的內容:

foreach (object o in children)
  Console.WriteLine(o != null ? o.GetType().FullName : "null");

它是object引用的數組,因此您將需要對其進行迭代並提取對象,例如:

// could also use IEnumerable or IEnumerable<object> in
// place of object[] here
object[] arr = (object[])foo["children"];

foreach(object bar in arr) {
    Console.WriteLine(bar);
}

如果知道對象是什么,則可以進行強制轉換-或可以使用LINQ OfType / Cast擴展方法:

foreach(string s in arr.OfType<string>()) { // just the strings
    Console.WriteLine(s);
}

或者您可以測試每個對象:

foreach(object obj in arr) { // just the strings
    if(obj is int) {
        int i = (int) obj;
        //...
    }
    // or with "as"
    string s = obj as string;
    if(s != null) {
        // do something with s
    }
}

除此之外,您將不得不添加更多細節...

我意識到該線程已經使用了一年多,但是我想發布一個解決方案,以防萬一有人試圖從使用Cook Computing XML-RPC庫返回的System.Object []中獲取數據。

一旦返回了Children對象,請使用以下代碼查看其中包含的鍵/值:

foreach (XmlRpcStruct rpcstruct in Children)
        {
            foreach (DictionaryEntry de in rpcstruct)
            {
                Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
            }
            Console.WriteLine();
        }

(請注意,我沒有在VS中測試此代碼,而是在這里處理內存)。

object[] children = (object[])foo["children"];
foreach(object child in children)
    System.Diagnostics.Debug.WriteLine(child.GetType().FullName);

這應該轉儲孩子的類名。

如果您要對foo [“ children”]進行foreach操作,那么就不會因為找不到數組而失敗,因為按照定義,數組有一個(除非我錯過了什么)。

“我知道子級包含數據,可能是嵌套數據,但是我不確定它是否是列表,字典,數組等”

所以childreen是IEnumerable或不是集合

試試這個代碼

void Iterate(object childreen)
{
  if(data is IEnumerable)
     foreach(object item in data)
      Iterate(item);
  else Console.WriteLine(data.ToString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM