4

I have an object which implements IList interface, I want to cast it to IList<object> or List<object>, I tried

IList<object> a=(IList<object>)b;
List<object> a=(IList<object>)b;
IList<object> a=(List<object>)b;
List<object> a=(List<object>)b;

These are not working. Please help, thanks. To clarify:

b is an object pass as parameter from outside. It implements IList interface. For example,

public class a
{
  string name;
  List<a> names;
}
public void func(object item)
{
  object dataLeaves = data.GetType().GetProperty("names").GetValue(dataInput, null);
  if (dataLeaves != null && dataLeaves.GetType().GetInterfaces().Any(t =>t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IList<>)))
  {
    List<object> a=(List<object>) dataLeaves; //Need to convert the dataLeaves to list or IList
  }
}

It's because mysql_fetch_object fetches a result row as an object. Others, such as mysql_fetch_array, fetch a result row as an associative array.

4

3 回答 3

16

如果现有对象未实现该接口,则无法将其转换为,但您可以使用 LINQ 轻松IList<object>构建新对象: List<object>

List<object> = b.Cast<object>().ToList();
于 2013-02-07T19:53:38.623 回答
3

找到了答案:

IEnumerable<object> a = dataLeaves as IEnumerable<object>;
于 2013-02-07T20:36:40.803 回答
0

一个IList根本不是一个IList<object>。对象实际上实现这两个接口的可能性极小,因此强制转换永远不会成功。您需要创建一个新的列表对象来实现IList<object>

IList<object> a= b.OfType<object>.ToList();
于 2013-02-07T19:54:52.270 回答