C#代码,将实体类打包成string类,也可将string类转换为实体类
目前支持常用的几种基本类型,需要其他自定义类型的,理论上也可以再进行添加
原理:T泛类 类反射
using System.Collections;
using System;
/**
* 实体类打包为string
**/
public class StringPacker
{
public static char SPLIT = ',';
/**
* 将实体类打包成string
**/
public static string Pack
(T obj)
{
string output = "";
if (obj != null)
{
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
{
output += p.GetValue(obj, null) + SPLIT.ToString();
}
output = output.TrimEnd(SPLIT);
}
return output;
}
/**
* 将string解包成实体类
**/
public static T Unpack
(string input, T obj)
{
if (input == null || input.Length <= 0)
return obj;
string[] split = input.Split(SPLIT);
int i = 0;
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
{
p.SetValue(obj, GetObject(p, split[i]), null);
i++;
}
return obj;
}
/**
* 类型支持列表
**/
private static object GetObject(System.Reflection.PropertyInfo p, string value)
{
switch (p.PropertyType.Name.ToString().ToLower())
{
case "int16":
return Convert.ToInt16(value);
case "int32":
return Convert.ToInt32(value);
case "int64":
return Convert.ToInt64(value);
case "string":
return Convert.ToString(value);
case "datetime":
return Convert.ToDateTime(value);
case "boolean":
return Convert.ToBoolean(value);
case "char":
return Convert.ToChar(value);
case "single":
return Convert.ToSingle(value);
case "double":
return Convert.ToDouble(value);
default:
return value;
}
}
private class MyObject
{
public int a { set; get; }
public float b { set; get; }
public double c { set; get; }
public string d { set; get; }
}
/**
* 使用示例
**/
public static void example()
{
MyObject obj = new MyObject() { a = 1, b = 1.1f, c = 1.2, d = "2" };
string pack = Pack
(obj);
print("pack:" + pack);
print("unpack:" + Unpack
(pack, new MyObject()));
}
}
参考:
http://www.cnblogs.com/chenwolong/p/fanshe.html