我想使用通用的 WriteList(List value) 函数通过 BinaryWriter 编写一个 List。这是我正在使用的代码:
public void WriteList<T>(List<T> value)
{
for (int i = 0; i < value.Count; i++)
{
_writer.Write(value[i]);
}
}
我收到的错误是:
Error 1 The best overloaded method match for 'System.IO.BinaryWriter.Write(bool)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'T' to 'bool'
BinaryFormatter 绝对不是一个选项。
最佳答案
我真的不认为你可以避免 BinaryFormatter。因为类型 T 可以是任何复杂类型,并且 T 的每个实例都可以表示内存中一个巨大的变量图。
所以您唯一的解决方案是将您的 T 实例转换为 byte[] 格式,最简单的解决方案是:BinaryFormatter
实际上 .Write() 方法只接受原始类型的原因是它知道如何将它们直接转换为 byte[](使用 Convert.ToXXX()),但它无法猜测泛型类型 T。
作为解决方法,您可以像这样定义一个接口(interface):
public interface IBinarySerializable
{
byte[] GetBytes();
}
然后在你的类中实现它:
public class MyClass: IBinarySerializable
{
public int X {get;set;}
public byte[] GetBytes()
{
return BitConverter.GetBytes(X); // and anyother
}
}
并将您的方法更改为:
public void WriteList<T>(List<T> value) where T:IBinarySerializable
{
for (int i = 0; i < value.Count; i++)
{
_writer.Write(value[i].GetBytes());
}
}
关于c# - 如何使用 BinaryWriter 编写列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6769245/