我为.net 2.0编写了这个类方法,以便从分隔的字符串创建对象,反之亦然。
但问题是,在Inherted类型的情况下,它们没有给出正确的结果,即继承的属性是最后一个,以“|”分隔的字符串形式提供的数据序列不起作用。
class A
{
int ID;
}
class B : A
{
string Name;
}
字符串是“1 | John”。方法的读取方式是name==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();
}
}