2010-10-25 73 views
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(); 
     } 
    } 

回答

2
  • 我不认为运行时向你保证,当你调用的GetProperties属性信息的对象将始终以相同的顺序。您将需要执行一些操作,比如获取属性名称列表,并对序列化和反序列化使用相同的排序。

  • 至少有3种方式来序列内置.NET对象是存在的,为什么你不使用的那些

一个理由