开发者

.Net - serialize objects

If i have objects with properties of type object开发者_运维知识库 or objects that are generics, how can i serialize this?

Eg.

public class MyClass
{
   public Object Item { get; set; }
}

or

public class MyClass<T>
{
   public T Item { get; set; }
}

EDIT

My Generic class now looks like this:

public class MyClass<T>
{
   public MySubClass<T> SubClass { get; set; }
}

public class MySubClass<T>
{
   public T Item { get; set; }
}

Additonal question: How can i change the element name for Item at runtime to typeof(T).Name?


Have you tried the [Serializable] attribute?

[Serializable]
public class MySerializableClass
{
   public object Item { get; set; }
}

[Serializable]
public class MySerializableGenericClass<T>
{
   public T Item { get; set; }
}

Although the generic class is only serializable if the generic type parameter is serializable as well.

Afaik there is no way to constrain the type parameter to be serializable. But you can check at runtime using a static constructor:

[Serializable]
public class MySerializableGenericClass<T>
{
   public T Item { get; set; }

   static MySerializableGenericClass()   
   {
      ConstrainType(typeof(T));
   }

   static void ConstrainType(Type type)
   {
      if(!type.IsSerializable)
         throw new InvalidOperationException("Provided type is not serializable");
   }
}


Use these methods to serialize\deserialize any object (even generics) to an XML file, though can be modified to suit other purposes:

public static bool SerializeTo<T>(T obj, string path)
{
    XmlSerializer xs = new XmlSerializer(obj.GetType());
    using (TextWriter writer = new StreamWriter(path, false))
    {
        xs.Serialize(writer, obj);
    }
    return true;
}

public static T DeserializeFrom<T>(string path)
{
    XmlSerializer xs = new XmlSerializer(typeof(T));
    using (TextReader reader = new System.IO.StreamReader(path))
    {
        return (T)xs.Deserialize(reader);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜