2009-06-30 54 views
0

下面的代码:麻烦迭代一个通用列表与自定义对象

ProductList products = xxx.GetCarProducts(productCount); 
    List<CarImageList> imageList = new List<CarImageList>(); 


    foreach(Product p in products) 
    { 
     string imageTag = HttpUtility.HtmlEncode(string.Format(@"<img src=""{0}"" alt="""">", ImageUrl(p.Image, false))); 

     imageList.Add(new CarImageList{ImageTag = imageTag}); 
     i++; 
    } 

在产品列表中像这样真正定义封面:

public class ProductList : List<Product> 
{ 
    static Random rand = new Random(); 

    public ProductList Shuffle() 
    { 
     ProductList list = new ProductList(); 
     list.AddRange(this); 

     for (int i = 0; i < list.Count; i++) 
     { 
      int r = rand.Next(list.Count - 1); 
      Product swap = list[i]; 
      list[i] = list[r]; 
      list[r] = swap; 
     } 

     return list; 
    } 

    public Product FindById(int id) 
    { 
     foreach (Product p in this) 
      if (p.Id == id) return p; 

     return null; 
    } 

    public Product GetRandom() 
    { 
     int r = rand.Next(this.Count - 1); 
     return this[r]; 
    } 
} 

所以为什么我得到的错误,当我尝试的foreach通过ProductList实例?

无法将类型'xxx.Product'转换为'Product'是我得到的错误。但是,如果ProductList真的是List,为什么在世界上它会有转换问题?

+0

是什么GetCarProducts看上去像人体?你在使用LinqToSQL吗?如果是这样,错误可能出现在GetCarProducts中,但直到您尝试迭代集合时才显示出来。 – tvanfosson 2009-06-30 02:37:22

+0

GetCarProducts返回类型ProductList。没有没有使用LINQ – PositiveGuy 2009-06-30 02:39:44

+0

试过这个,但没有运气,说它无法转换ProductList products = GetCarProducts(productCount);列表 prods =产品; – PositiveGuy 2009-06-30 02:40:47

回答

0

在第一个示例的上下文中,在我看来Product在第二个示例的上下文中是与Product类型不同的Product类型。你确定你有你的名字空间吗?

0

这听起来像你有两个不同的类,都称为“产品”,但在不同的命名空间/类。 (公共)嵌套类是一个坏主意,因为它们可能会加剧这种问题......我会检查你对Product的引用实际上是同一个类。

编辑:

void Main() 
{ 
    ProductList products = new ProductList(); 
    products.Add(new Product("foo")); 
    products.Add(new Product("bar")); 

    foreach(Product p in products) 
    { 
     Console.WriteLine(p.Name); 
    } 
} 

// Define other methods and classes here 
public class ProductList : List<Product> 
{ /* [snip] the other stuff is irrelevant */ } 

public class Product 
{ 
    public Product(string name) 
    { Name = name; } 
    public string Name; 
} 
1

我觉得你xxx.GetCarProducts(productCount);可返回List<Product>参考比你ProductList类较少定义的,在你的GetCarProducts方法意味着你可能做的新List<Product>代替new ProductList()

如果有什么事情你可以张贴的GetCarProducts