How to cast one compound custom type to another

痴心易碎 提交于 2021-02-20 17:04:11

问题


I'm trying to write a converter class for custom types--converting one type (and all of its properties) to another type that has matching properties.

The problem comes in when the property is also a custom type, rather that a simple type.
The custom types are all identical, except they live in different namespaces in the same solution.
TypeTwo objects are Webservice references.

For example

public TypeOne ConvertToTypeTwo (TypeTwo typeTwo)
{
var typeOne = new TypeOne();
typeOne.property1 = typeTwo.property1; //no problem on simple types
typeOne.SubType = typeTwo.SubType; //problem!
...
}

The error I get on the line above is:

Error 166 Cannot implicitly convert type 'TypeTwo.SubType' to 'TypeOne.SubType'

I've tried casting like so

typeOne.SubType = (TypeOne)typeTwo.SubType;

But get:

Error 167 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType'

And like so

typeOne.SubType = typeTwo.SubType as TypeOne;   

But get:

Error 168 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

I'm not sure what other options I have, or if I'm just doing something fundamentally wrong. Any thoughts?


回答1:


You can't do that. Even if the two types have exactly the same layout (same fields with same types), you cannot cast from one to another. It's impossible.

What you have to do instead is to create a converter (either as method, a separate class or a cast operator) that can translate from a type to another.




回答2:


If the two subtypes are different types, you'll have to write a separate converter to convert between the two types.

For example:

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.
}


来源:https://stackoverflow.com/questions/10741794/how-to-cast-one-compound-custom-type-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!