将一个类转换为另一个类 [英] Convert One class to another class

查看:98
本文介绍了将一个类转换为另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用WCF服务的WPF客户端,该服务再次调用另一个驻留在另一个位置的wcf服务(WPF - > WCF Service1(虚拟) - > Wcf Service2(另一个位置))。由于设计,我不能直接从WPF调用服务2,不应暴露WPF客户端,所以我采取这种方式。



现在,Service 2将数据协定作为响应对象返回给service1。我必须在服务1中转换该数据协定并将响应发送回WPF客户端。我在service1中创建了具有完全相同属性的相同datacontract。有没有人知道转换自定义类型的任何方法,我想到循环并手动分配每个属性,但我相信会有一些更好的解决方案。任何人都可以提供一些可用的例子。



提前致谢。

解决方案

首先,类成员之间转换的需要(你不转换类型,你转换实例)是一个非常明确的代码设计缺陷的迹象。



如果两种类型不相关(一种不直接或间接地从另一种类型派生),则不能只在它们之间进行转换。您所能做的就是创建目标类型的全新实例并从源实例复制所有数据。此外,您可能需要或可能不需要深度克隆某些数据。顺便说一句,请看我过去的答案:

如何为列表类实现ICloneable? [ ^ ]。



对于某些语法糖,您可以开发一种或另一种类型的类型转换运算符。请参阅:

http://msdn.microsoft.com/en-us /library/85w54y0a.aspx [ ^ ]。



参见:

http://en.wikipedia.org/wiki/Deep_copy#Deep_copy [ ^ ],

http://en.wikipedia。 org / wiki / Syntactic_sugar [ ^ ]。



但首先要做的事情。我再说一遍,首先要检查你的数据结构的架构和设计,这可能是一个很大的缺陷。



-SA

I have a WPF client which calls WCF service, that service again calls another wcf service which is residing in another location (WPF --> WCF Service1(dummy) --> Wcf Service2 (Another location)). I can't directly call service 2 from WPF due to design, WPF client should not be exposed, so I am taking this route.

Now, Service 2 returns a data contract to service1 as response object. I have to convert that data contract in service 1 and send the response back to WPF client. I created same datacontract in service1 with exact same properties. Does any one know any way to convert the custom type, I thought of looping and assigning each property manually, but I believe there would be some better solution. Could any one suggest with some example available please.

Thanks in advance.

解决方案

First of all, the need in "conversion" between class members (you do not "convert" types, you "convert" the instances) is a pretty sure sign of a flaw in the code design.

If two types are not related (one is not derived from another directly or indirectly) you cannot just make a cast between them. All you can do is to create a brand new instance of the target type and copy all data from source instance. Moreover, you may or may not need to deep-clone some data. Please see my past answer, by the way:
How to implement ICloneable for a List Class?[^].

For some syntactic sugar, you can develop a type conversion operator in one or another type. Please see:
http://msdn.microsoft.com/en-us/library/85w54y0a.aspx[^].

See also:
http://en.wikipedia.org/wiki/Deep_copy#Deep_copy[^],
http://en.wikipedia.org/wiki/Syntactic_sugar[^].

But first things first. I repeat, first thing would be to review your architecture and design of your data structures, it can be a big flaw.

—SA


这篇关于将一个类转换为另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆