编组时强制转换异常
本文关键字:转换 异常 | 更新日期: 2023-09-27 18:31:25
我目前正在使用写入缓冲区的结构。当将结构读回我的应用程序时,我得到以下异常:
无法将类型为"System.Windows.Documents.TextStore"的对象强制转换为类型"System.Version"。
法典
转换结果时会引发异常 ( (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
)。
protected static T ReadStruct<T>(Stream input)
where T : struct
{
Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
input.Read(buffer, 0, buffer.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return result;
}
使用的数据结构
/// <summary>
/// The header for all binary files
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet=CharSet.Ansi)]
public unsafe struct BinaryHeader
{
public const String MAGIC_KEY = "TABF";
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
String _Magic;
Version _Version;
DateTime _Timestamp;
Guid _Format;
Int64 _Reserved0;
Int64 _Reserved1;
/// <summary>
/// The magic value for the test automation binary
/// </summary>
public String Magic
{
get
{
return _Magic;
}
}
/// <summary>
/// The version of the assembly ( used for debugging )
/// </summary>
public Version AssemblyVersion { get { return _Version; } }
/// <summary>
/// The formatGuid of the current binary
/// </summary>
public Guid FormatGuid { get { return _Format; } }
/// <summary>
/// The timestamp of the file
/// </summary>
public DateTime Timestamp { get { return _Timestamp; } }
public BinaryHeader(Guid formatGuid)
{
_Reserved0 = 0;
_Reserved1 = 0;
_Version = BinaryBase.AssemblyVersion;
_Format = formatGuid;
_Timestamp = DateTime.Now;
_Magic = MAGIC_KEY;
}
}
使用这种方法烹饪自己的二进制序列化方案是可以的,但您必须了解限制。 一个核心问题是它只能处理可 blitable 值,简单的值类型值。 pinvoke 封送器对具有 [MarshalAs] 属性的字符串有一个解决方法。 没有可用于版本类的此类解决方法。 存储在结构中的指针值将被写入文件。 当你读回它时,更正常的事故是你会得到一个访问违规异常。 除非你有幸指针碰巧取消引用存储在 GC 堆上的有效对象。 在您的案例中是文本存储类型的对象。
当然,这并不完全是幸运的。 你必须重新考虑你的方法,_Version领域必须去。 不要犹豫,使用 BinaryFormatter 类,这正是它的目的。