2017-03-15 65 views
0

我有一個對象,它是一個List訪問列表內的對象

object myobject; // 

我知道myObject的是

List<double> or List<string> 

我需要打印這樣的事情;

for (int i = 0; i < myobject.count()+ i++) 
{ 
    string str = myobject[i].toString(); 
} 

但我不知道如何計算對象,並接取一些myObject的[I]

+0

您不能訪問的MyObject但因爲它是類型的對象。簡單地將其轉換爲使用它之前的任何集合類型http://stackoverflow.com/questions/632570/cast-received-object-to-a-listobject-or-ienumerableobject – Master

+0

可能的重複[Cast cast a object to a列表或IEnumerable ](http://stackoverflow.com/questions/632570/cast-received-object-to-a-listobject-or-ienumerableobject) – Igor

回答

1

所有你需要做的是將它轉換爲你期待的,所以如果你知道列表類型的要成爲字符串列表,你做這樣的事情:

List<string> myList = (List<string>)myobject; 

for (int i = 0; i < myList.Count(); i++) 
{ 
    string str = myList[i]; 
} 

這是因爲如果你真的不知道,如果你得到的名單是雙重或字符串:

List<string> myStringList = new List<string>(); 
List<double> myDoubleList = new List<double>(); 

try { 

    myStringList = (List<string>)myobject; 

    for (int i = 0; i < myStringList.Count(); i++) 
    { 
     Console.WriteLine(myStringList[i]); 
    } 
} 
catch (InvalidCastException) 
{ 
    myDoubleList = (List<double>)myobject; 

    for (int i = 0; i < myDoubleList.Count(); i++) 
    { 
     Console.WriteLine(myDoubleList[i]); 
    } 
} 
+0

但他不知道它是否是一個字符串列表 –

+0

公平如果他不知道它是哪一種,我補充了第二種方法。 – CNuts

0

由於myobject的類型沒有任何屬性,稱爲Count。你可以嘗試像以下:

var list = myobject as List<int>(); 
if(list == null) 
{ 
    // The cast failed. 
    // If the method's return type is void change the following to return; 
    return null; 
} 
for (int i = 0; i < list.Count; i++) 
{ 
    string str = list[i].toString(); 
} 
1

我建議提取的一般方法:

// think on turning the method into static 
private void PerformList<T>(List<T> list) { 
    // try failed 
    if (null == list) 
    return; 

    // foreach (var item in list) {...} may be a better choice 
    for (int i = 0; i < list.Count; ++i) { 
    string str = list[i].ToString(); 

    ... 
    } 
} 

... 

object myobject = ...; 

// Try double 
PerformList(myobject as List<double>); 
// Try string 
PerformList(myobject as List<string>);