Cannot implicitly convert type 'System.Collections.Generic.List<Library.Product>' to 'System.Collections.Generic.List<Library.IHierarchicalEntity>' [duplicate]
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>();
精彩评论