JAN*_*JAN -6 .net c# linq casting
我有两个彼此没有联系的类:
public class A
{
public String Address {get;set}
}
public class B
{
public String Address {get;set}
}
List<A> addressList = DB.Addresses.GetAll();
Run Code Online (Sandbox Code Playgroud)
当我做
List<B> addressListOther = addressList.Cast<B>().ToList();
Run Code Online (Sandbox Code Playgroud)
输出是:
附加信息:无法将"A"类型的对象强制转换为"B"类型.
知道怎么解决这个问题吗?
您可以使用Select()而不是这种方式:
List<B> addressListOther = addressList.Select(a => new B { Address = a.Address}).ToList();
Run Code Online (Sandbox Code Playgroud)
或者你可以explicit operator在课堂上覆盖B:
public static explicit operator B(A a) // explicit A to B conversion operator
{
return new B { Address = a.Address };
}
Run Code Online (Sandbox Code Playgroud)
然后:
List<B> addressListOther = aList.Select(a => (B)a).ToList();
Run Code Online (Sandbox Code Playgroud)
这个例外的原因:
Cast将抛出InvalidCastException,因为它试图转换A为object,然后将其转换为B:
A myA = ...;
object myObject = myA ;
B myB= (B)myObject; // Exception will be thrown here
Run Code Online (Sandbox Code Playgroud)
此异常的原因是,盒装值只能拆分为完全相同类型的变量.
附加信息:
Cast<TResult>(this IEnumerable source)如果您感兴趣,以下是该方法的实现:
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);
}
Run Code Online (Sandbox Code Playgroud)
如你所见,它返回CastIterator:
static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
foreach (object obj in source) yield return (TResult)obj;
}
Run Code Online (Sandbox Code Playgroud)
看看上面的代码.它将使用foreach循环遍历源,并将所有项转换为object,然后转换为(TResult).
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |