WCF序列化依賴屬性詳細介紹
WCF開發(fā)框架作為一款功能強大的跨平臺解決方案,其中包含的操作方法和各種知識是相當繁雜的。我們需要不斷的去熟練操作,才能掌握這一知識點。我們先來了解下WCF序列化依賴屬性相關概念。#t#
眾所周知.NetFramework中存在著兩種依賴屬性,他們也分別集成著不同但名稱相同的依賴對象:
System.Windows.DependencyProperty:System.Windows.DependencyObject
System.Workflow.ComponentModel.DependencyProperty:System.Workflow.ComponentModel.DependencyObject
System.Window.DependencyProperty主要用于WPF中,我們可以以注冊的形式聲明這種‘特別’的屬性,聲明中可以設置Metadata,PropertyChangeCallBack...等等,讓我能用幾句簡單的代碼來實現強大的WPF操作。
System.Workflow.ComponentModel.DependencyProperty相對于前者,是一個簡化版本,只可以在聲明中可以設置Metadata,但對于WorkflowFoundation這就足夠用了。
兩種依賴屬性對各自的技術,都不同程度的提供了很好的支持,讓我們在實際開發(fā)中能夠更高效的書寫代碼,但是我們能不能像一般的屬性那樣隨意聲明,并運用?至少在WCF序列化依賴屬性中我們很難使用這種特殊的屬性。
以工作流中的System.workflow.ComponentModel.DependencyObject為例
如果我們想像一般自定義類那樣,在聲明完DataContract和DataMember后便可在基于WCF的應用程序中應用,會遇到UserData這個繼承于IDictionary的討厭屬性在WCF中無法序列化。如:
- [DataContract]
- public class WorkFlowParameter :
DependencyObject- {
- public static readonly Dependency
Property 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序列化依賴屬性應用中,我們只能無語了。
為了使得包含依賴屬性的自定義類能在WCF中正常使用
我們可以以下面的步驟自己動手寫序列化方法
1.在自定義類中繼承ISerializable接口,并實現構造函數以及GetObjectData方法
如:
- public class WorkFlowParameter :
DependencyObject,ISerializable- {
- //在Deserialize時使用
- public WorkFlowParameter(SerializationInfo
info, StreamingContext context)- {
- ID = new Guid (info.GetString("ID"));
- ParameterName = info.GetString("ParameterName");
- }
- //在Serialize時調用,把除了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.經過我們自定義序列化后,我們可以正常使用了
如果你遇到類型XXXX不能為 ISerializable,且不能具有 DataContractAttribute 屬性這時候我們需要在WCF序列化依賴屬性中,我們可以把類中的
- [DataContract]去掉
- [DataContract]//去掉
- public class Work
FlowParameter :
DependencyObject
再試試,大功告成了。呵呵。