代码之家  ›  专栏  ›  技术社区  ›  user366312

“|”的泛型对象-分隔字符串序列化

  •  0
  • user366312  · 技术社区  · 14 年前

    我为.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();
            }
        }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   rerun    14 年前
    • 我认为运行时不能保证调用getproperties时,property info对象的顺序总是相同的。您需要做一些事情,比如获取属性名列表,对它们进行排序,并使用相同的排序进行序列化和反序列化。