WebService中Hashtable用法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebService中Hashtable用法相关的知识,希望对你有一定的参考价值。
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);//告知需要解析的type 11 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序列化之后写进writer 12 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 //DicToHashtable 13 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用法的主要内容,如果未能解决你的问题,请参考以下文章