【问题标题】:How to retrieve a list stored in an Object class如何检索存储在 Object 类中的列表
【发布时间】:2020-07-22 23:05:45
【问题描述】:
public class A
{
    public long TestCaseId { get; set; }
    public byte TestCaseNumber { get; set; }

    public object FetchList { get; set; }
} 
class Program
{
    static void Main(string[] args)
    {
        List<int> a = new List<int>(){ 1, 2, 3, 4 };
        List<A> Objectlst = new List<A>();
        Objectlst .Add(new A { TestCaseId = 1, TestCaseNumber = 1, FetchList = a });
        foreach (var item in Objectlst)
        {
            Console.WriteLine(item.FetchList);
        }
    }
}

有一个类列表A。如果我将一个通用列表分配给对象数据类型FetchList, 有人能告诉我如何通过这个属性FetchList检索存储在列表中的所有值吗?

【问题讨论】:

标签: c# list object console


【解决方案1】:
foreach (var item in Objectlst)
{
    var list = item.FetchList as List<int>;
    if (list != null)
        foreach (int num in list)
            Console.WriteLine(num);
}

【讨论】:

  • 非常感谢!但是如果我不知道列表示例的类型怎么办,在这里你用作 List 但是如果你不知道列表的类型,即它不是通用的一些随机类类型怎么办。
  • @SiddharthDwivedi 那么你不应该使用object。当然,您可以在运行时通过反射发现类型信息,但 C# 是一种强类型语言。所以使用编译时类型安全是我的建议。
猜你喜欢
  • 2013-10-03
  • 2019-10-06
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多