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#程序设计有所帮助。