Csharp/C#教程:C#实现实体类与字符串互相转换的方法分享

本文实例讲述了C#实现实体类与字符串互相转换的方法。分享给大家供大家参考。具体实现方法如下:

usingSystem; usingSystem.Collections.Generic; usingSystem.Text; namespacePackDLL.Data.ConvertData { ///<summary> ///实体类、字符串互相转换 ///</summary> publicclassPackReflectionEntity<T> { ///<summary> ///将实体类通过反射组装成字符串 ///</summary> ///<paramname="t">实体类</param> ///<returns>组装的字符串</returns> publicstaticstringGetEntityToString(Tt) { System.Text.StringBuildersb=newStringBuilder(); Typetype=t.GetType(); System.Reflection.PropertyInfo[]propertyInfos=type.GetProperties(); for(inti=0;i<propertyInfos.Length;i++) { sb.Append(propertyInfos[i].Name+":"+propertyInfos[i].GetValue(t,null)+","); } returnsb.ToString().TrimEnd(newchar[]{','}); } ///<summary> ///将反射得到字符串转换为对象 ///</summary> ///<paramname="str">反射得到的字符串</param> ///<returns>实体类</returns> publicstaticTGetEntityStringToEntity(stringstr) { string[]array=str.Split(','); string[]temp=null; Dictionary<string,string>dictionary=newDictionary<string,string>(); foreach(stringsinarray) { temp=s.Split(':'); dictionary.Add(temp[0],temp[1]); } System.Reflection.Assemblyassembly=System.Reflection.Assembly.GetAssembly(typeof(T)); Tentry=(T)assembly.CreateInstance(typeof(T).FullName); System.Text.StringBuildersb=newStringBuilder(); Typetype=entry.GetType(); System.Reflection.PropertyInfo[]propertyInfos=type.GetProperties(); for(inti=0;i<propertyInfos.Length;i++) { foreach(stringkeyindictionary.Keys) { if(propertyInfos[i].Name==key.ToString()) { propertyInfos[i].SetValue(entry,GetObject(propertyInfos[i],dictionary[key]),null); break; } } } returnentry; } ///<summary> ///转换值的类型 ///</summary> ///<paramname="p"></param> ///<paramname="value"></param> ///<returns></returns> staticobjectGetObject(System.Reflection.PropertyInfop,stringvalue) { switch(p.PropertyType.Name.ToString().ToLower()) { case"int16": returnConvert.ToInt16(value); case"int32": returnConvert.ToInt32(value); case"int64": returnConvert.ToInt64(value); case"string": returnConvert.ToString(value); case"datetime": returnConvert.ToDateTime(value); case"boolean": returnConvert.ToBoolean(value); case"char": returnConvert.ToChar(value); case"double": returnConvert.ToDouble(value); default: returnvalue; } } } }

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:C#中List和数组之间转换的方法C#实现char字符数组与字符串相互转换的方法C#几种截取字符串的方法小结C#字符串数组转换为整形数组的方法C#字符串、数组和List的截取和转换实例

标签: 字符 实体类 字符串 实体 方法

C语言中栈和队列实现表达式求值的实例

使用Libmicrohttpd搭建内嵌(本地)服务器的方法

上述就是C#学习教程:C#实现实体类与字符串互相转换的方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/906753.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐