Cast in List object
I have an interface A, class B inherits from interface A. I have a 开发者_StackOverflowlist of objects:
List<B> myB;
List<A> myA;
I want to assign myB to myA but I get a error "Cannot implicit convert type 'B' to 'A':
myA = myB;
Please help me. Thanks.
You need to convert each element of the list. It cannot be automatically converted for you. Easiest would be Linq:
myA = myB.Cast<A>().ToList();
Update: This question: Why is this cast not possible? discusses it in more detail.
It might help you: Cast List<int> to List<string> in .NET 2.0
IList<T>
is not covariant, where as IEnumerable<T>
is, you can do the following..
void Main()
{
IEnumerable<B> myB= new List<B>();
IEnumerable<A> myA = myB;
}
public interface A
{
}
public class B :A
{
}
see this previous SO Question
You need to make a way to convert between type A
and type B
.
There is no way to assign a list of one type to another, unless the type B
is the same as type A
.
You can use the Cast<T>
operator for derived types:
class A {}
class AA : A {}
List<AA> aas = new List<AA> {new AA()};
List<A> bunchofA = aas.Cast<A>().ToList();
This only works when casting to less derived types (from descendant to ancestor). This won't work:
List<A> bunchofA = new List<A> {new A()};
List<AA> aas = bunchofA.Cast<AA>.ToList();
Because the compiler cannot know what to do to make the extra bits that AA
has from A
.
You can also, in a rather contrived way, use implicit conversion:
class A
{
}
class B
{
public static implicit operator B(A a)
{
return new B();
}
public static implicit operator A(B a)
{
return new A();
}
}
List<B> bs = new List<B>{new B()};
List<A> bunchOfA = bs.Select(b => (A)b).ToList();
This will work in either direction, but might cause confusion, so it is better to create explicit conversion methods and use those.
That is correct. List is a list of Apples and List is a list of .. err .. batmans! You cannot try to put one into the other.
Technically, you cannot refer to one as the other!
精彩评论