標籤:解決方案 returns 用法 script ash summary www gets uil
知識轉自這裡
code slice 01
1 /// <summary> 2 /// 還原序列化資料 3 /// </summary> 4 /// <param name="sXml"></param> 5 /// <param name="type"></param> 6 /// <returns></returns> 7 private T DeSerializer<T>(String sXml, Type type) 8 { 9 XmlReader reader = XmlReader.Create(new StringReader(sXml));//還有的解釋用FileStream,應該無所謂,沒查出serializer.Deserialize參數類型10 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);//告知需要解析的type11 object obj = serializer.Deserialize(reader);//解析後的obj可以直接轉換為type類型12 return (T)obj;13 }
code slice 02
1 /// <summary> 2 /// HashTable序列化Xml內容 3 /// </summary> 4 /// <param name="_ContextXml"></param> 5 /// <returns></returns> 6 [WebMethod(Description = "WebService傳遞HashTable值")] 7 public Boolean SetHashValue(String _ContextXml) 8 { 9 Hashtable _Hash = new Hashtable();10 DictionaryEntry[] _DictArray = DeSerializer<DictionaryEntry[]>(_ContextXml, typeof(DictionaryEntry[]));11 foreach (DictionaryEntry _Entity in _DictArray)12 {13 _Hash.Add(_Entity.Key, _Entity.Value);14 }15 return true;16 }
註:此函數的功能是避免以Hashtable為參,WebService不允許。
code slice 03
1 /// <summary> 2 /// 序列化資料類型 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="objToXml"></param> 6 /// <returns></returns> 7 public String Serializer<T>(T objToXml) 8 { 9 System.IO.StringWriter writer = new System.IO.StringWriter();10 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(objToXml.GetType());11 serializer.Serialize(writer, objToXml);//將ibjToXml序列化之後寫進writer12 return writer.GetStringBuilder().ToString();13 }
註:System.Xml.Serialization.XmlSerializer序列化
code slice 04
1 private void ClientSetHashValue() 2 { 3 4 //DemoService.Service1 _Service = new DemoService.Service1(); 5 Hashtable _Hash = new Hashtable(); 6 _Hash.Add("User", "yifeng"); 7 _Hash.Add("Address", "this is yifeng‘s Address"); 8 _Hash.Add("Age", "20");
//HashtableToDic 9 //DictionaryEntry必須先定義大小10 DictionaryEntry[] _DictEntry = new DictionaryEntry[_Hash.Count];11 _Hash.CopyTo(_DictEntry, 0);//大小和Hashtable不一致也可12 //DicToHashtable13 String _Context = Serializer<DictionaryEntry[]>(_DictEntry);14 Boolean _Status = _Service.SetHashValue(_Context);15 }
Hashtable在WebService中無法使用copy函數拷貝內容至DictionaryEntry,解決方案見code slice 05(關於WebService通訊,後續會記錄)
code slice 05
1 proname.DictionaryEntry[] _DictEntry = new proname.DictionaryEntry[_Hash.Count]2 int i = 0;3 foreach(string keys in _Hash.Keys)4 {5 _DictEntry[i] = new proname.DictionaryEntry();//重點!6 _DictEntry[i].Key = keys;7 _DictEntry[i].Value = _Hash[keys];8 i++;9 }
WebService中Hashtable用法