无法将“System.Collections.Generic.List`1[System.Object]”类型的对象转换为“System.Collections.Generic.List`1[customType]”类型

问题描述 投票:0回答:1

我有 ArrayList,其中包含 4 个项目。每个项目的类型都是

List<object>
。我正在尝试使用下面的代码从 ArrayList 获取第一项。但它会抛出错误

无法转换类型的对象 'System.Collections.Generic.List

1[System.Object]' to type 'System.Collections.Generic.List
1[自定义类型]

调用代码-

ArrayList arrayList = BusinessLayer.GetData();
List<CustomType> tempList = (List<CustomType>)arrayList[0];

称为代码逻辑-

if (connection.State == System.Data.ConnectionState.Closed)
                    connection.Open();

                var command = connection.CreateCommand();
                command.CommandText = "EXEC SP_GET_DATA @id";
                command.Parameters.Add(new SqlParameter("@id", id));
                using (var reader = command.ExecuteReader())
                {
                    var customTypeList = ((IObjectContextAdapter)context)
                            .ObjectContext
                            .Translate<object>(reader)
                            .ToList();

                    arrayList.Add(customTypeList);
        
                   reader.NextResult();

                   var customType2List = ((IObjectContextAdapter)context)
                            .ObjectContext
                            .Translate<object>(reader)
                            .ToList();

                    arrayList.Add(customType2List);
              }

我正在返回数组列表,并希望在调用代码时获取数据。我不想在调用的代码中使用模型。我明白,我们可以在调用的代码中使用模型,但我必须验证是否使用 ArrayList,我们可以取回数据吗?我希望我解释清楚了。

这里我试图将

List<object>
从 ArrayList 转换为
List<CustomType>

c# generics arraylist
1个回答
0
投票

您必须首先显式地转换回对象列表。然后使用 Cast 为自定义类型。

ArrayList arrayList = new();

arrayList.Add(new List<object>() { new Person() { FirstName = "Bob", LastName = "NewHart"} });

List<Person> tempList = ((List<object>)arrayList[0]).Cast<Person>().ToList();

Console.WriteLine(tempList[0].FirstName);
Console.ReadLine();

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.