im having issues with the following interface and a class:
public interface IRelated
{
}
public class BaseItem:IRelated
{
public string Name{get;set;}
public List<IRelated> RelatedItems{get;set;}
}
Now when i try to do in other classes the following it gives me a compilation error:
List<IRelated> listofrelateditems=new List<BaseItem>();
Cannot implicity convert type
List<BaseItem>
toList<IRelated>
The reason of the interface is that in the future maybe i will have another class that can be Related to this BaseItem.
You just can't do that - even the generic covariance in .NET 4 won't help you, because List<T>
is a class and even IList<T>
is invariant as it has T
coming "in" as well as going out.
It's precisely because you might have a new implementation of IRelated
in the future that you can't do that. Consider:
List<IRelated> listOfRelatedItems = new List<BaseItem>();
listOfRelatedItems.Add(new OtherRelatedItem());
where OtherRelatedItem
implements IRelated
but doesn't derive from BaseItem
. Now you've got a List<BaseItem>
which contains something other than a BaseItem
! In other words, it breaks type safety.
Basically you'll have to create a List<IRelated>
instead of a List<BaseItem>
.
For more on generic variance and why it's sometimes applicable and sometimes not, go to the NDC 2010 videos page and search for "variance" to find the video of a presentation I gave on the topic last year.
Like you yourself said: You may have another class that can be IRelated
. How are you going to add an instance of such a class to a List<BaseItem>
?
You will have to write:
List<IRelated> listofrelateditems = new List<IRelated>();
改成:
List<IRelated> listofrelateditems=new List<IRelated>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.