C#写对象的二进制文件 [英] C# writing object to binary file
问题描述
我要在二进制file.My结构看起来像这样写的对象。
I have to write an object in to binary file.My struct looks like this.
Struct Company
{
int numberofemployees
list of Struct Employee.
}
Struct Employee
{
string EmployeeName;
string Designation;
}
什么是做上述操作的最佳方法是什么? 此致 拉朱
What is the best way to do the above operation? Regards Raju
推荐答案
究竟你要的输出是什么样子?您可以手动编写(见Lirik的答案),或者如果你想运行库支持,也许像protobuf网。
What exactly do you want the output to look like? You can write it manually (see Lirik's answer), or if you want runtime support, perhaps something like protobuf-net.
这将是微不足道的,如果你正在使用类(我希望你确实应该)做的,但另外protobuf网V2(仅可作为源的时刻),应该与原样。
This would be trivial to do if you were using classes (which I expect you actually should be), but additionally protobuf-net v2 (only available as source at the moment) should work with that "as is".
有关信息,这里是我会怎么做它作为类:
For info, here is how I would do it as classes:
public class Company
{
private readonly List<Employee> employees = new List<Employee>();
public List<Employee> Employees { get { return employees;}}
}
public class Employee
{
public string EmployeeName {get;set;}
public string Designation {get;set;}
}
这可与序列化属性的装饰,或者(再次使用protobuf网V2)像这样的测试(其中通过):
This could be decorated with serialization attributes, or (again, using protobuf-net v2) something like this test (which passes):
[Test]
public void CanSerializeCompany()
{
var model = TypeModel.Create();
model.Add(typeof(Company), false).Add("Employees");
model.Add(typeof(Employee), false).Add("EmployeeName", "Designation");
model.CompileInPlace();
Company comp = new Company {
Employees = {
new Employee { Designation = "Boss", EmployeeName = "Fred"},
new Employee { Designation = "Grunt", EmployeeName = "Jo"},
new Employee { Designation = "Scapegoat", EmployeeName = "Alex"}}
}, clone;
using(var ms = new MemoryStream()) {
model.Serialize(ms, comp);
ms.Position = 0;
Console.WriteLine("Bytes: " + ms.Length);
clone = (Company) model.Deserialize(ms, null, typeof(Company));
}
Assert.AreEqual(3, clone.Employees.Count);
Assert.AreEqual("Boss", clone.Employees[0].Designation);
Assert.AreEqual("Alex", clone.Employees[2].EmployeeName);
}
(并写入46字节)
(and writes 46 bytes)
它的应该的私人领域,结构等的工作 - 我得看看......
It should work with private fields, structs, etc - I'd have to take a look...
如果你能添加属性,那么你就需要手动设置模式(第4行)。的code剩下的只是显示全往返使用。
If you are able to add attributes, then you don't need to set up the model manually (the first 4 lines). The rest of the code is just showing full round-trip usage.
这篇关于C#写对象的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!