WCF 中序列化自定义依赖属性类
眾所周知.NetFramework中存在著兩種依賴屬性,他們也分別集成著不同但名稱相同的依賴對象:
System.Windows.DependencyProperty:System.Windows.DependencyObject
System.Workflow.ComponentModel.DependencyProperty:System.Workflow.ComponentModel.DependencyObject
System.Window.DependencyProperty主要用于WPF中,我們可以以注冊的形式聲明這種‘特別’的屬性,聲明中可以設(shè)置Metadata,PropertyChangeCallBack...等等,讓我能用幾句簡單的代碼來實現(xiàn)強大的WPF操作。
?
System.Workflow.ComponentModel.DependencyProperty相對于前者,是一個簡化版本,只可以在聲明中可以設(shè)置Metadata,但對于WorkflowFoundation這就足夠用了。
?
兩種依賴屬性對各自的技術(shù),都不同程度的提供了很好的支持,讓我們在實際開發(fā)中能夠更高效的書寫代碼,但是我們能不能像一般的屬性那樣隨意聲明,并運用?至少在WCF中我們很難使用這種特殊的屬性。
以工作流中的System.workflow.ComponentModel.DependencyObject為例
如果我們想像一般自定義類那樣,在聲明完DataContract和DataMember后便可在基于WCF的應(yīng)用程序中應(yīng)用,會遇到UserData這個繼承于IDictionary的討厭屬性在WCF中無法序列化。如:
[DataContract]
public class WorkFlowParameter : DependencyObject
{
public static readonly DependencyProperty IDProperty =
??????????? DependencyProperty.Register("ID", typeof(Guid), typeof(WorkFlowParameter),new PropertyMetadata("UserDefinedProperty"));
?
?? [DataMember]
???public Guid ID
??????? {
??????????? get { return (Guid)GetValue(IDProperty); }
??????????? set { SetValue(IDProperty, value); }
??????? }
}
?
像這樣一個看起來很平常的類,在WCF應(yīng)用中,我們只能無語了。
?
為了使得包含依賴屬性的自定義類能在WCF中正常使用
我們可以以下面的步驟自己動手寫序列化方法
1.在自定義類中繼承ISerializable接口,并實現(xiàn)構(gòu)造函數(shù)以及GetObjectData方法
如:
public class WorkFlowParameter : DependencyObject,ISerializable
{
//在Deserialize時使用
?????? public WorkFlowParameter(SerializationInfo info, StreamingContext context)
??????? {
??????????? ID = new Guid (info.GetString("ID"));
??????????? ParameterName = info.GetString("ParameterName");
??????? }
????????
?????????//在Serialize時調(diào)用,把除了UserData以外我們自定義的屬性添加進來進行序列化
???public void GetObjectData(SerializationInfo info, StreamingContext context)
??????? {
??????????? IList<DependencyProperty> properties = DependencyProperty.FromType(this.GetType());
??????????? if(properties.Count > 0)
??????????? {
??????????????? foreach(DependencyProperty property in properties)
??????????????? {
???????????????????? if(property.Name != "UserData")
???????????????{
??????????????????????????? info.AddValue(property.Name, GetValue(property));
???????????????????? }
????????????????}
??????????? }
??????? }
}
?
?2.經(jīng)過我們自定義序列化后,我們可以正常使用了
?
如果你遇到類型XXXX不能為 ISerializable,且不能具有 DataContractAttribute 屬性這時候我們需要在WCF服務(wù)中,我們可以把類中的
[DataContract]去掉
?
[DataContract]//去掉
public class WorkFlowParameter : DependencyObject
?
?
再試試,大功告成了。呵呵。
轉(zhuǎn)載于:https://www.cnblogs.com/ystlife/archive/2009/11/15/1603568.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的WCF 中序列化自定义依赖属性类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]字符编码,ansi, unicod
- 下一篇: 【自然框架】之通用权限(四):角色表组