如果我的对象具有object类型的属性或泛型的对象,我该如何序列化它?
例如
public class MyClass
{
public Object Item { get; set; }
}
或
public class MyClass<T>
{
public T Item { get; set; }
}
修改
My Generic类现在看起来像这样:
public class MyClass<T>
{
public MySubClass<T> SubClass { get; set; }
}
public class MySubClass<T>
{
public T Item { get; set; }
}
Additonal question:如何在运行时将Item的元素名称更改为typeof(T).Name?
答案 0 :(得分:6)
您是否尝试过[Serializable]
属性?
[Serializable]
public class MySerializableClass
{
public object Item { get; set; }
}
[Serializable]
public class MySerializableGenericClass<T>
{
public T Item { get; set; }
}
虽然泛型类只是可序列化的,但泛型类型参数也是可序列化的。
Afaik没有办法将类型参数限制为可序列化。但是您可以在运行时使用静态构造函数进行检查:
[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");
}
}
答案 1 :(得分:1)
使用这些方法将任何对象(甚至泛型)序列化\反序列化为XML文件,但可以修改以适应其他目的:
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);
}
}