J*****n 发帖数: 4859 | 1 I have a class and its derived class
[Serializable(), StructLayout(LayoutKind.Sequential)]
class A{DateTime i}
[Serializable(), StructLayout(LayoutKind.Sequential)]
class B : A {Int32 j}
List p = new List();
Now, I add three element in the p and then serilize p into a binary file
called out.bin.
Now, I would get the third element in the p from the out.bin without reading
the first two elements.
using (BinaryReader reader = new BinaryReader(File.Open("out.bin", FileMode.
Open)))
{
Int32 len = (Int32)reader.BaseStream.Length;
reader.BaseStream.Seek(len - 12, SeekOrigin.Begin);
byte[] buffer = reader.ReadBytes(12);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
output = ((B)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(
TSOHLC)))
}
however, it doesn't return the correct answer. I remember in C++, a empty
vector contains 3 pointer. In C#, List must contains some extra elements.
Now, what's the correct way to realize my goal?
Thank you. | H*******g 发帖数: 6997 | | G***l 发帖数: 355 | 3 我不知道有没有办法可以按你那样做,但是就算有一种方法可以让你跳到后面读,你这
种做法也不是正经的做法。serialize是把整个object作为一个整体存起来,你去中间
读不管能不能work,都破坏了这个integrity。而且c#的api肯定也不保证某些你想象的
顺序或者部分读取一定成功。你这种使用api但是又绕过正确使用方法试图去hack感觉
像是在写c++程序,而且是用很难维护的方式去写。
之前都是废话,说点解决方案。最简单的,如果性能没有明显影响的话,就把整个list
读进来。既然你把一个list序列化了,那我想在你application的life cycle里一般不
会只用其中一个位置的element,这样在需要别的位置的element的时候也不用再去读盘
了,说不定总的性能还更好了。如果你实在需要读第n个element,那就不要用list的序
列化,自己把一个list里的element按顺序写。如果你能确定每个element大小一样的话
,读的时候自然可以跳到想要的位置去读单个element。
reading
【在 J*****n 的大作中提到】 : I have a class and its derived class : [Serializable(), StructLayout(LayoutKind.Sequential)] : class A{DateTime i} : [Serializable(), StructLayout(LayoutKind.Sequential)] : class B : A {Int32 j} : List p = new List(); : Now, I add three element in the p and then serilize p into a binary file : called out.bin. : Now, I would get the third element in the p from the out.bin without reading : the first two elements.
| J*****n 发帖数: 4859 | 4
list
受教了。谢谢
【在 G***l 的大作中提到】 : 我不知道有没有办法可以按你那样做,但是就算有一种方法可以让你跳到后面读,你这 : 种做法也不是正经的做法。serialize是把整个object作为一个整体存起来,你去中间 : 读不管能不能work,都破坏了这个integrity。而且c#的api肯定也不保证某些你想象的 : 顺序或者部分读取一定成功。你这种使用api但是又绕过正确使用方法试图去hack感觉 : 像是在写c++程序,而且是用很难维护的方式去写。 : 之前都是废话,说点解决方案。最简单的,如果性能没有明显影响的话,就把整个list : 读进来。既然你把一个list序列化了,那我想在你application的life cycle里一般不 : 会只用其中一个位置的element,这样在需要别的位置的element的时候也不用再去读盘 : 了,说不定总的性能还更好了。如果你实在需要读第n个element,那就不要用list的序 : 列化,自己把一个list里的element按顺序写。如果你能确定每个element大小一样的话
| W********n 发帖数: 254 | 5 可以做一个custom serializable的List,GetObjectData里实现你自己的方法生成
binary data,这样你就可以控制只写你自己需要的element,固定长度等等。 | W********n 发帖数: 254 | 6 估计实现generic的list会比较复杂。。。good luck |
|