2

In my program, I will get a var object at run time and I would like to write it to a binary file, but I couldn't write var variable by using BinaryWriter. It gives a compile error that cannot convert from 'object' to 'bool'. How to solve it?

BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)
var obj = Convert.ChangeType(property.GetValue(objectToWrite, null), property.PropertyType);
writer.Write(obj); //Compile error
4

2 回答 2

2

var在这种情况下,将解析为object,因为这是GetValue返回的内容。没有BinaryWriter.Write接受的重载object。你接下来想要什么取决于几件事:

  • 如果您的意图是将一个非常简单的值(单个bool,int等 - 支持的东西BinaryWriter)写入文件,那么您将必须打开该简单值的类型;一个厚颜无耻的方法是使用dynamic,它将在运行时计算出来:

    writer.Write((dynamic)obj); // not great, but should work
    
  • 如果您的意图是编写一段复杂的数据(a class/ structetc),那么您不应该使用BinaryWriter- 您应该使用serializer。也许BinaryFormatter(尽管这有一些严重的问题让我不愿意推荐它)或 protobuf-net,或类似的

于 2013-05-22T11:00:37.957 回答
0
BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create);
var obj = Convert.ChangeType(property.GetValue(objectToWrite, null), property.PropertyType);
writer.Write(obj);

尝试使用obj而不是var.

于 2013-05-22T10:49:54.733 回答