开发者

How to Typecast a list?

I have a class in third party DLL.

Class A
{

}

I need to decorate it so I created the local instance of it and used it

class B
{

}

The DLL contains a function which gives me the list of A. But If I try to use it as follows

B listofB = Dll.FindAllA()

I got error that 开发者_开发知识库cannot implicitly convert DLL.A to Proj.B

There is no difference between the structure of these two classes. How can I convert it?


If A and B don't have anything in common (except they look the same), the compiler is out of luck. Options:

  • inheritance (sometimes)
  • add a conversion operator to either of the types
  • add a ToA etc extension method if the types are outside of your control
  • try automapper
  • use serialization (there are ways of making some serializers work with different names etc)

I would go for the first 2 options first. Note that with List<T> you can use convert all, i.e.:

List<A> orig = ...
List<B> copy = orig.ConvertAll(a => (B)a);// assumes a conversion operator exists

For other types, the LINQ Select method is equivalent to ConvertAll.


I think you partly gave the answer yourself, because you are talking about 'decorating'. Implement B or an descendant of B in a way that it decorates an A and wrap the elements of the returned collection in instances of B:

public class B
{
    // Methods of B
}

public class AToBAdapter : B
{
    A a;

    public AToBAdapter(A a)
    {
        this.a = a;
    }

    // Override methods of B to map to A
}

Now with this adapter in place, you can change the list of As to Bs:

B[] listofB = Dll.FindAllA().Select(a => new AToBAdapter(a) as B).ToArray();


you can overload the cast operator on class B:

public static implicit operator B(A e)
{
    return new B(e.Property1, e.Property2);
}

BTW, you should only use implicit if there can be no data loss and you dont expect an exception, otherwise change to explicit: (B)A


C# is covariant and will not support implicit conversion of collections. Though this issue has been addressed in C#4.0 in a slightly different manner. For example the following code will throw a compile time exception

  public class A
  {

  }
   public class B : A
   {

   }

   List<B> obj1 = new List<B>();
   List<A> obj2 = obj1;

Though B is derived from A the implicit conversion will not take place. It has to be explicitly converted like below.

   List<A> obj2 = obj1.ConvertAll(b => (A)b);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜