对象内的访问列表

时间:2017-03-15 21:04:31

标签: c#

我有一个List的对象

object myobject; // 

我知道myobject是

List<double> or List<string>

我需要打印这样的东西;

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

但我不知道如何计算物体,并且接触了一些myobject [i]

3 个答案:

答案 0 :(得分: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]);
    }
}  

答案 1 :(得分: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>);

答案 2 :(得分: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();
}