下面的代码:麻烦迭代一个通用列表与自定义对象
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,为什么在世界上它会有转换问题?
是什么GetCarProducts看上去像人体?你在使用LinqToSQL吗?如果是这样,错误可能出现在GetCarProducts中,但直到您尝试迭代集合时才显示出来。 – tvanfosson 2009-06-30 02:37:22
GetCarProducts返回类型ProductList。没有没有使用LINQ – PositiveGuy 2009-06-30 02:39:44
试过这个,但没有运气,说它无法转换ProductList products = GetCarProducts(productCount);列表 prods =产品; –
PositiveGuy
2009-06-30 02:40:47