在没有泛型的情况下将A类转换为B类 [英] Cast class A to class B without generics
问题描述
我有两个彼此没有联系的班级:
I have two classes that have no connection to one another :
public class A
{
public String Address {get;set}
}
public class B
{
public String Address {get;set}
}
List<A> addressList = DB.Addresses.GetAll();
我这样做
List<B> addressListOther = addressList.Cast<B>().ToList();
输出为:
其他信息:无法将类型为"A"的对象转换为类型"B".
Additional information: Unable to cast object of type 'A' to type 'B'.
任何想法如何解决?
推荐答案
您可以使用Select()
代替这种方式:
You can use Select()
instead of that way:
List<B> addressListOther = addressList.Select(a => new B { Address = a.Address}).ToList();
或者您可以在类B
中覆盖explicit operator
:
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 };
}
然后,
List<B> addressListOther = aList.Select(a => (B)a).ToList();
此异常的原因:
The reason of this exception:
Cast
将抛出InvalidCastException
,因为它试图将A
转换为object
,然后将其转换为B
:
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:
这是 Cast<TResult>(this IEnumerable source)
Cast<TResult>(this IEnumerable source)
方法,如果您感兴趣的话:
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);
}
如您所见,它返回CastIterator
:
static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
foreach (object obj in source) yield return (TResult)obj;
}
看上面的代码.它将使用foreach
循环遍历源,并将所有项目转换为object
,然后转换为(TResult)
.
Look at the above code. It will iterate over source with foreach
loop, and converts all items to object
, then to (TResult)
.
这篇关于在没有泛型的情况下将A类转换为B类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!