You can use Select()
instead of that way:
List<B> addressListOther = addressList.Select(a => new B { Address = a.Address}).ToList();
Or you can override explicit operator
in class B
:
public static explicit operator B(A a) // explicit A to B conversion operator
{
return new B { Address = a.Address };
}
And, then:
List<B> addressListOther = aList.Select(a => (B)a).ToList();
The reason of this exception:
Cast
will throw InvalidCastException
, because it tries to convert A
to object
, then cast it to B
:
A myA = ...;
object myObject = myA ;
B myB= (B)myObject; // Exception will be thrown here
The reason of this exception is, a boxed value can only be unboxed to a variable of the exact same type.
Additional Information:
Here is the implemetation of the Cast<TResult>(this IEnumerable source)
method, if you interested:
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) {
IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
if (typedSource != null) return typedSource;
if (source == null) throw Error.ArgumentNull("source");
return CastIterator<TResult>(source);
}
As you see, it returns CastIterator
:
static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
foreach (object obj in source) yield return (TResult)obj;
}
Look at the above code. It will iterate over source with foreach
loop, and converts all items to object
, then to (TResult)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…