将对象转换为列表<int>



我已经将List of int存储在一个对象类型中,并试图使用以下代码将对象转换为List of int。每次,它都抛出一个强制转换异常。

List<int> ObjToList(object array)
{
try
{
List<object> list = new List<object>();
var enumerator = ((IEnumerable)array).GetEnumerator();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
var val = list.Cast<int>().ToList();
return val;
}
catch (Exception ex)
{
return new List<int>();
}
}

某种具有模式匹配的通用转换器
只是为了好玩:

static List<T> ObjToList<T>(object obj)
{
switch (obj)
{
case List<T> list:
// we passed a list, so just return it as is
return list;
case IEnumerable<T> genericEnumerable:
// we passed a generic sequence, and items type is what we need
return genericEnumerable.ToList();
case IEnumerable enumerable:
// we passed some sequence, and we don't know, what is the type of any particular item;
// using OfType<T> instead of Cast<T> allows to pass sequences that
// contain items with different types
return enumerable.OfType<T>().ToList();
default:
// we passed none of above;
// just return empty list
return new List<T>(0);
}
}

样品:

// displays 3
Console.WriteLine(ObjToList<int>(new List<int> { 1, 2, 3 }).Count);
// displays 3 
Console.WriteLine(ObjToList<int>(new[] { 1, 2, 3 }).Count);
// displays 2, one item is not an integer
Console.WriteLine(ObjToList<int>(new ArrayList { 1, "2", 3 }).Count); 
// displays 0, all items are characters, but not integers
Console.WriteLine(ObjToList<int>("123").Count); 
// displays 0, not a sequence at all
Console.WriteLine(ObjToList<int>(123).Count); 
// displays 0, not a sequence at all
Console.WriteLine(ObjToList<int>(null).Count); 

回答您的问题

List<int> ObjToList(object array)
{
var result = new List<int>();
if (array is IEnumerable<int> valueSet)
{
result.AddRange(valueSet);
}
return result;
}

然而,正如评论中提到的,不确定你为什么要这样做,当你调用它时,对象是什么。

你可以试试这个

var array = new int[2] { 1, 2 };
//convert the array to object (for testing purpose)
object arrayasobject = array; 
//check whether the object is int[]
if (arrayasobject.GetType() == typeof(int[]))
{
//approach #1 .. cast to List<int>
var list1 = new List<int>(arrayasobject as int[]);
//approach #2 .. using LINQ
var list2 = (arrayasobject as int[]).ToList();
}

最新更新