0
我已经编写了.net 2.0的这个类方法来从'|'分隔的字符串创建对象,反之亦然。通用对象到'|' - 分隔字符串序列化
但问题是,在Inherted类型的情况下它们没有给出正确的结果,即继承的属性最后到来,并且以'|'分隔的字符串形式提供的数据序列不起作用。
例如:
class A
{
int ID;
}
class B : A
{
string Name;
}
字符串为 “1 |约翰”。该方法读取的名称== 1和ID ==“John”。
请告诉我该怎么做。
public class ObjectConverter<T>
{
public static T TextToObject(string text)
{
T obj = Activator.CreateInstance<T>();
string[] data = text.Split('|');
PropertyInfo[] props = typeof(T).GetProperties();
int objectPropertiesLength = props.Length;
int i = 0;
if (data.Length == objectPropertiesLength)
{
for (i = 0; i < objectPropertiesLength; i++)
{
props[i].SetValue(obj, data[i], null);
}
}
return obj;
}
public static string ObjectToText(T obj)
{
StringBuilder sb = new StringBuilder();
Type t = typeof(T);
PropertyInfo[] props = t.GetProperties();
int i = 0;
foreach (PropertyInfo pi in props)
{
object obj2 = props[i++].GetValue(obj, null);
sb.Append(obj2.ToString() + "|");
}
sb = sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}