Reflection 通用对象到'|'-分隔字符串序列化

Reflection 通用对象到'|'-分隔字符串序列化,reflection,serialization,c#-2.0,Reflection,Serialization,C# 2.0,我已经为.net 2.0编写了此类方法,用于从“|”分隔的字符串创建对象,反之亦然 但问题是,对于内插类型,它们没有给出正确的结果,即继承属性排在最后,以“|”分隔字符串形式提供的数据序列不起作用 例如: class A { int ID; } class B : A { string Name; } 字符串是“1 | John”。这些方法的读取方式为name==1和ID==John 请告诉我怎么做 public class ObjectConverter<T>

我已经为.net 2.0编写了此类方法,用于从“|”分隔的字符串创建对象,反之亦然

但问题是,对于内插类型,它们没有给出正确的结果,即继承属性排在最后,以“|”分隔字符串形式提供的数据序列不起作用

例如:

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();
        }
    }
公共类ObjectConverter
{
公共静态T TextToObject(字符串文本)
{
T obj=Activator.CreateInstance();
string[]data=text.Split(“|”);
PropertyInfo[]props=typeof(T).GetProperties();
int objectPropertiesLength=props.Length;
int i=0;
if(data.Length==objectPropertiesLength)
{
对于(i=0;i
  • 我认为运行时不能保证调用getproperties时,property info对象的顺序总是相同的。您将需要执行类似于获取属性名列表的操作对它们进行排序,并使用相同的排序进行序列化和反序列化

  • 至少有3种方法可以序列化内置到.net中的对象。您为什么不使用其中一种方法