我正在尝试为自定义类型编写一个转换器类——将一种类型(及其所有属性)转换为另一种具有匹配属性的类型。
当属性也是自定义类型而不是简单类型时,问题就出现了。
自定义类型完全相同,只是它们位于同一解决方案中的不同命名空间中。
TypeTwo 对象是 Web 服务引用。
例如
public TypeOne ConvertToTypeTwo (TypeTwo typeTwo)
{
var typeOne = new TypeOne();
typeOne.property1 = typeTwo.property1; //no problem on simple types
typeOne.SubType = typeTwo.SubType; //problem!
...
}
我在上面一行得到的错误是:
Error 166 Cannot implicitly convert type 'TypeTwo.SubType' to 'TypeOne.SubType'
我试过这样转换
typeOne.SubType = (TypeOne)typeTwo.SubType;
但是得到:
Error 167 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType'
像这样
typeOne.SubType = typeTwo.SubType as TypeOne;
但是得到:
Error 168 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
我不确定我还有哪些其他选择,或者我是否只是在做一些根本性的错误。 有什么想法吗?
最佳答案
如果这两个子类型是不同的类型,您将不得不编写一个单独的转换器来在这两种类型之间进行转换。
例如:
public TypeOne ConvertToTypeTwo (TypeTwo typeTwo)
{
var typeOne = new TypeOne();
typeOne.property1 = typeTwo.property1; //no problem on simple types
typeOne.SubType = ConvertToTypeTwo(typeTwo.SubType); //problem!
}
public TypeOneSubtype ConvertToTypeTwo(TypeTwoSubType typeTwo)
{
var subOne = new TypeOneSubType;
subOne.property1 = typeTwo.property1;
// etc.
}
关于c# - 如何将一种复合自定义类型转换为另一种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741794/