Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

c# - 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();

When I do

List<B> addressListOther = addressList.Cast<B>().ToList();

the output is :

Additional information: Unable to cast object of type 'A' to type 'B'.

Any idea how to fix that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...