[英]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. 我得到了程序集1和程序集2.它包含两个相同名称和相同内部结构的类型。
Assembly 3 reference 1 and 2, and create a object of one of them. 程序集3引用1和2,并创建其中一个对象。 Now I want to cast it to the other from assembly 2. 现在我想把它从汇编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 . 您可以使用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);
这两种类型不同,因为它们位于不同的程序集中,您必须将Property复制到Property。
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. 请注意,这会创建一个新的TypeTwo
实例,因此您对其所做的更改将不会反映在原始TypeOne
实例中。
I got one dirty solution: 我有一个脏的解决方案:
Use XML serialize the obj1, hack into the XML and replace "namespace1" with "namespace2". 使用XML序列化obj1,攻击XML并将“namespace1”替换为“namespace2”。 And then deserialize the XML into obj2. 然后将XML反序列化为obj2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.