[英]How to load same plugins from 2 different assemblies, and serializing and deserializing types between the two? C# .net
[英]How to cast between 2 types of the same name and internal sturcture but from different assemblies?
我得到了程序集1和程序集2.它包含兩個相同名稱和相同內部結構的類型。
程序集3引用1和2,並創建其中一個對象。 現在我想把它從匯編2中轉移到另一個。
以下是假代碼:
assembly1.namespace1.typeXXX obj1 = new assembly1.type1();
assembly2.namespace2.typeXXX obj2 = obj1; <=== error here
怎么做?
謝謝!
您可以使用AutoMapper 。
如果屬性的名稱相同,則它就像這樣簡單:
Mapper.CreateMap<assembly1.type1, assembly2.type1>();
var obj2 = Mapper.Map<assembly1.type1, assembly2.type1>(obj1);
這兩種類型不同,因為它們位於不同的程序集中,您必須將Property復制到Property。
您可以定義自定義轉換運算符 ,但我認為在這種情況下只會增加混淆。 我的問題是,為什么你定義了兩個相同(但是分開)的類? 為什么不直接使用其中一個呢?
另一種方法是在類型之間進行映射。 如果您無法控制其源代碼,可以使用擴展方法執行此操作:
public static class TypeOneExtensions
{
public static TypeTwo AsTypeTwo(this TypeOne typeOne)
{
return new TypeTwo
{
PropertyA = typeOne.PropertyA,
PropertyB = typeOne.PropertyB,
...
};
}
}
請注意,這會創建一個新的TypeTwo
實例,因此您對其所做的更改將不會反映在原始TypeOne
實例中。
我有一個臟的解決方案:
使用XML序列化obj1,攻擊XML並將“namespace1”替換為“namespace2”。 然后將XML反序列化為obj2。
同樣的問題發生在我身上。
這段代碼也許可以幫到你!
using type1=assembly1.namespace1.typeXXX;
using type2=assembly2.namespace2.typeXXX;
或者,你可以讀這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.