开发者

How to cast between 2 types of the same name and internal sturcture but from different assemblies?

I got assembly 1 and assembly 2. which contain 2 types of the same name and identical internal structure.

Assembly 3 reference 1 and 2, and create a object of one of them. Now I want to cast it to the other from ass开发者_运维知识库embly 2.

Below is the fake code:

assembly1.namespace1.typeXXX obj1 = new assembly1.type1();
assembly2.namespace2.typeXXX obj2 = obj1;   <=== error here

How to do it?

Thanks!


You could use AutoMapper.
If the properties are named the same, it is as simple as this:

Mapper.CreateMap<assembly1.type1, assembly2.type1>();
var obj2 = Mapper.Map<assembly1.type1, assembly2.type1>(obj1);


This two types are different because of they are in different assemblies, you will have to copy Property to Property.


I got one dirty solution:

Use XML serialize the obj1, hack into the XML and replace "namespace1" with "namespace2". And then deserialize the XML into obj2.


You could define custom casting operators, but I think in this case that would only add confusion. My question is, why have you defined two identical (but separate) classes? Why not just use one of them?

Another alternative is to map between the types. If you don't have control over their source code, you could do this with an extension method:

public static class TypeOneExtensions
{ 
    public static TypeTwo AsTypeTwo(this TypeOne typeOne)
    {
        return new TypeTwo
        {
            PropertyA = typeOne.PropertyA,
            PropertyB = typeOne.PropertyB,
            ...
        };
    }
}

Note though that this creates a new instance of TypeTwo, so changes you make to it won't be reflected in the original TypeOne instance.


The same question happens to me.

This code maybe can help you!

using type1=assembly1.namespace1.typeXXX;
using type2=assembly2.namespace2.typeXXX;

Or, You can read this

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜