制作可索引的IList

时间:2016-01-21 16:58:45

标签: c# list indexing

        IMS_ProductController pc = new IMS_ProductController();
        IList<IMS_Product>  newrec= new List<IMS_Product>();
        newrec.Add(new IMS_Product()
        {
            Name = "Bobo",
            Description = "Some desc",
            Url = "http",
            ProductInfoUrl = "http"
        })
        IMS_Product ip = new IMS_Product();
        IEnumerator<IMS_Product> myprod = newrec.GetEnumerator();
        myprod.MoveNext();
        foreach (var prop in ip.GetType().GetProperties())
        {
            Console.WriteLine(prop.Name); //this works. Returns "Name","Description","URL","ProductInfoURL"
            Console.WriteLine(myprod.Current.Name); //This works. Returns "Bobo" each time
            Console.WriteLine(myprod.Current[prop.Name]); //this does NOT work. IList is not indexable. 
        }

如何在foreach工作中制作第3行?我需要做什么来构建可索引列表/数组/什么?

谢谢! 克里斯

1 个答案:

答案 0 :(得分:1)

我认为您需要使用GetValue method来执行以下操作:

//Loop through objects
foreach(IMS_Product prod in newrec) 
{
    //Loop through properties
    foreach (var prop in typeof(IMS_Product).GetProperties()) 
    {
         //Print property name
         Console.WriteLine(prop.Name);

         //Print property value
         Console.WriteLine(prop.GetValue(prod));
    }
}