【问题标题】:Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.Collections.Generic.List`1[customType]无法将“System.Collections.Generic.List`1[System.Object]”类型的对象转换为“System.Collections.Generic.List`1[customType]”
【发布时间】:2021-12-28 17:40:02
【问题描述】:

我有包含 4 个项目的 ArrayList。每个项目的类型都是 List<object> 。我正在尝试使用以下代码从 ArrayList 获取第一项。但它会引发错误

无法转换类型的对象 'System.Collections.Generic.List1[System.Object]' to type 'System.Collections.Generic.List1[CustomType]

调用代码-

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 并希望在调用代码时取回数据。我不想在调用代码中使用模型。我知道,我们可以在调用代码中使用模型,但我必须验证是否使用 ArrayList,我们可以取回数据吗?希望我解释清楚。

我在这里尝试将 List&lt;object&gt; 从 ArrayList 转换为 List&lt;CustomType&gt;

【问题讨论】:

  • var tempList = arrayList[0].Cast&lt;CustomType&gt;().ToList();
  • @SandeepJadhav 盲目地使用 object 当你知道类型几乎总是错误的方法时。
  • @SSD 所以对索引 1 到 3 重复 arrayList[index].Cast&lt;OtherCustomType&gt;().ToList(); 及其各自的目标类型以创建其他 3 个列表
  • 现在是 2021 年。当 ArrayList 过时时,“业务层”甚至都不是一件事——你是怎么发现自己在这里的?!您可以做些什么来重写此代码以对开发人员更友好?一个充满 list 的数组列表是相当强烈的代码气味
  • 在将数据放入 arraylist 时,我对每个项目进行了强制转换 - 这真的是您在 2021 年编写的代码吗?我认为向我们展示该代码是值得的,因此我们可以建议如何使用现代 .net 的构造重写它 - 但首先向我们展示请求的屏幕截图

标签: c# generics arraylist


【解决方案1】:

您必须首先显式转换回对象列表。然后使用 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; }
}

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2012-05-22
    相关资源
    最近更新 更多