English 中文(简体)
如何将一种化合物习惯类型投射到另一种化合物习惯类型上
原标题:How to cast one compound custom type to another
  • 时间:2012-05-24 16:43:24
  •  标签:
  • c#

我试图写一个转换器类, 用于自定义类型, 将一种类型( 及其所有属性) 转换为具有匹配属性的另一种类型 。

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.

例如,例如

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

上面一行的错误是:

错误166 无法默认转换类型 Type 2. SubType 到 Type One.SubType

我试过这样投

typeOne.SubType = (TypeOne)typeTwo.SubType;

但获取 :

167 错误 167 无法转换类型 Type 2.SubType 到 Type One.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

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

最佳回答

您无法做到这一点。 即使这两种类型有“ 精确 < / 具体地” 相同的布局( 相同类型的字段), 您也可以“ em> 不能 / 坚固的播客 < / 坚固的 > 。 这是不可能的 。

相反,您需要做的是创建一个转换器(作为方法、单独的分类或投影操作员),能够从一种类型转换成另一种类型。

问题回答

如果两个子类型是不同的类型,则您必须写一个单独的转换器,才能在两种类型之间转换。

例如:

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签