开发者

Cannot implicitly convert type 'System.Collections.Generic.List<Library.Product>' to 'System.Collections.Generic.List<Library.IHierarchicalEntity>' [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

In C#, why can't a List<string> object be stored in a List<object> variable

I am having the following code.

   public class Manufacturer :  IHierarchicalEntity
    {
        public string ManufacturerName
        {
            get
            {
                return _manfuacturerName;
            }
            set
            {
                _manfuacturerName = value;
            }
        } private string _manfuacturerName;

        public List<Product> Products
        {
            get
            {
                return _products;
            }
        } private List<Product> _products;

        #region IHierarchicalEntity Members

        public List<IHierarchicalEntity> Children
        {
            get
            {
                return Products; //This is where I get the compiler error
           开发者_如何学JAVA }
        }

        #endregion
    }

    public class Product :  IHierarchicalEntity{}

    public interface IHierarchicalEntity
    {
        List<IHierarchicalEntity> Children { get; }
    }

I get a compiler exception that

Cannot implicitly convert type System.Collections.Generic.List<Library.Product> to System.Collections.Generic.List<Library.IHierarchicalEntity>

Both Manufacturer and Product are of type IHierarchicalEntity. Why is it not taking the List<Product> as List<IHierarchicalEntity> ?


This conversion is not possible, otherwise you could add a OtherHierarchicalEntity to List<Product> so its not safe. You can cast explicitly and return a new list:

  return Products.Cast<IHierarchicalEntity>().ToList();


Try doing:

return Products.ToList<IHierarchicalEntity>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜