Type casting to another with the same properties

醉酒当歌 提交于 2020-01-16 07:18:11

问题


In one section of my application, I use type generated from xsd scheme - I have 2 version of schemas 2008 and 2009 - type I use is DatumType - in every scheme this type contain the same properties - they are exact, except namespaces. Is there any way how to cast DatumType (2008) to DatumType (2009) so I can work in my application only with one type, instead of two?

I am working with c# and win forms, thanks!


回答1:


No, there is no way to cast one to the other, because these are two unrelated types, as far as the compiler knows.

If the fields of the target type are assignable, you can write a short method that uses reflection to copy the fields.

You could also build code that saves objects of the source type to XML, and reads that XML into the objects of the target type. This is slightly more fragile, because it relies on the presence of identical fields and the fact that they are converted to XML in the same way.




回答2:


It seems to me the easiest thing to do would be to build a small method to convert one type to the other (since they all share properties), or, if you have access to the source, implement an interface so that you can use the two classes as that interface.

In other words, if we have two classes, B and C, which inherit interface A (which contains all the properties we're interested in), we can typecast any object of those two classes as an A.




回答3:


You can pre-process your XML file with a simple XSLT that corrects the namespace differences.

The part 1 of 2 of Identity explain how to do it. Basically a transform has templates that matches elements and give an output for each matched element. The trick is to have a specific template to match the Datum elements and transform them, and a generic transform that matches all kind of elements and simply copy them.

If you don't have experience with XSLT, don't be afraid. It's easier to learn than you can expect. You can use a tutorial like XSLT tutorial which will allow you to understand the 'Identity' explanation.

You can use XslCompiledTransform Class to apply the transform.

You can use Visual Studio to test and debug your XSLT file.



来源:https://stackoverflow.com/questions/10218543/type-casting-to-another-with-the-same-properties

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