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




















