I have the following:
public interface ICartItem
{
string Name { get; set; }
}
public class CartItem : ICartItem
{
public string Name { get; set; }
}
I then create a开发者_如何学C List and cast it to an interface:
IList<CartItem> items = new List<CartItem>()
{
new CartItem() { Name = "MyItem" }
};
IList<ICartItem> cartItems = items.Cast<ICartItem>().ToList();
Is there a way to cast it back again like illustrated below?
IList<CartItem> newList = cartItems as IList<CartItem>;
Do you need a copy of the list?
If yes, and you are sure that there are only CartItems within the list you can do it with
IList<CartItem> newList = cartItems.Cast<CartItem>().ToList();
But i think you'd like it a little more robust. In that case you can try it with
cartItems.Where(item => item as CartItem != null).Cast<CartItem>().ToList();
But i think you need to create a new list. I can't think of a way to work on the same with an IList
interface (IEnumerable<T>
works as shown above).
This is not a logical issue because you cannot make sure that all the items in the 'cartItems' list can be casting to 'CartItem' type.
Basically, the answer is no, IList<ICartItem> cannot be cast back to IList since CartItem is not the only type that might implement ICartItem. The cast cannot be type checked by the compiler since it does't know what will be inside the list at runtime.
In C# 4, you can do this:
IEnumerable<CartItem> items = new List<CartItem>
{
new CartItem() { Name = "MyItem" }
};
IEnumerable<ICartItem> cartItems = items;
(i.e. no need for the use of .Cast<ICartItem>().ToList())
Note that the interface is IEnumerable<> and not IList<> since only some interfaces were made covariant in C# 4 (the full list cn be found here: http://msdn.microsoft.com/en-us/library/dd233059.aspx).
However, even in C# 4, adding the following line will cause the compiler to fail:
IEnumerable<CartItem> newList = cartItems;
精彩评论