泛型类序列化
- 泛型类可以标记为可序列化,但只有当泛型类型参数可序列化时,泛型类才可序列化。如下:class One
{
public string Name { get; set; }
}
[Serializable]
class Program<T>
{
public T Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Program<One> pro = new Program<One>();
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
try
{
formatter.Serialize(stream, pro);
}
catch (SerializationException ex)
{
// 程序集“MyConsoleApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类 // 型“MyConsoleApplication.One”未标记为可序列化。
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
为了使泛型类可以序列化,有以下几种方法:
- 将泛型类型参数定义的成员变量标识为NonSerialized,这样泛型类型参数的类型就不会影响到泛型类的序列化。class One
{
public string Name { get; set; }
}
[Serializable]
class Program<T>
{
// T不会影响Program<T>序列化,因为此成员变量被标识为不可序列化
[NonSerialized]
public T Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Program<One> pro = new Program<One>();
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, pro);
Console.ReadLine();
}
} - 将泛型类型参数进行约束,使其必须继承ISerializable。class One : ISerializable
{
public string Name { get; set; }
#region ISerializable 成员
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
}
#endregion
protected One(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
}
}
[Serializable]
class Program<T> where T : ISerializable
{
public T Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Program<One> pro = new Program<One>();
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, pro);
Console.ReadLine();
}
} - 为泛型类添加静态初始化器,进行泛型类型参数检查,如果是不可序列化,则抛出SerializationException异常。class One
{
public string Name { get; set; }
}
[Serializable]
class Program<T>
{
static Program()
{
ContrainType(typeof(T));
}
static void ContrainType(Type type)
{
if (!type.IsSerializable)
{
throw new SerializationException(type.Name + "不可序列化");
}
if (type.IsGenericType)
{
Type[] typeArr = type.GetGenericArguments();
Array.ForEach(typeArr, ContrainType);
}
}
public T Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
try
{
Program<One> pro = new Program<One>();
}
catch (Exception ex)
{
// “MyConsoleApplication.Program`1”的类型初始值设定项引发异常。
Console.WriteLine(ex.Message);
// One不可序列化
Console.WriteLine(ex.InnerException.Message);
}
Console.ReadLine();
}
}