无法将类型'int'隐式转换为LittleEndian ByteOrder

时间:2014-07-20 14:10:14

标签: c# binaryreader

我的加载RAW图像功能有问题。我不明白错误的原因。它向我显示了这个错误:

  

无法隐式转换类型' int'到' Digital_Native_Image.DNI_Image.Byteorder'

public void load_DNI(string ficsrc)
{
    FileStream FS = null;
    BinaryReader BR = null;
    int width = 0;
    int height = 0;
    DNI_Image.Datatype dataformat = Datatype.SNG;
    DNI_Image.Byteorder byteformat = Byteorder.LittleEndian;

    FS = new FileStream(ficsrc, System.IO.FileMode.Open);
    BR = new BinaryReader(FS);

    dataformat = BR.ReadInt32();
    byteformat = BR.ReadInt32();
    width = BR.ReadInt32();
    height = BR.ReadInt32();

    // fermeture des fichiers
    if ((BR != null))
        BR.Close();
    if ((FS != null))
        FS.Dispose();

    // chargement de l'_image
    ReadImage(ficsrc, width, height, dataformat, byteformat);
}

1 个答案:

答案 0 :(得分:1)

int无法隐式转换为enum。您需要在此处添加显式强制转换:

dataformat = (Datatype.SNG)BR.ReadInt32();
byteformat = (Byteorder)BR.ReadInt32();

阅读Casting and Type Conversions (C# Programming Guide)了解详情。

但是,请注意,if (BR != null)检查不是必需的,这实际上不是处理IDisposable对象的正确方法。我建议你重写这段代码以使用using blocks。这样可以确保FSBR得到妥善处理:

int width;
int height;
Datatype dataformat;
Byteorder byteformat;

using (var FS = FileStream(ficsrc, System.IO.FileMode.Open))
using (var BR = new BinaryReader(FS))
{

    dataformat = (Datatype.SNG)BR.ReadInt32();
    byteformat = (Byteorder.LittleEndian)BR.ReadInt32();
    width = BR.ReadInt32();
    height = BR.ReadInt32();
}

// chargement de l'_image
ReadImage(ficsrc, width, height, dataformat, byteformat);

但似乎您可以通过重构ReadImage方法来使用相同的BinaryReader来改善这一点。然后你可以重写这个方法看起来更像这样:

using (var FS = FileStream(ficsrc, System.IO.FileMode.Open))
using (var BR = new BinaryReader(FS))
{

    var dataformat = (Datatype.SNG)BR.ReadInt32();
    var byteformat = (Byteorder.LittleEndian)BR.ReadInt32();
    var width = BR.ReadInt32();
    var height = BR.ReadInt32();
    ReadImage(ficsrc, width, height, dataformat, byteformat, BR);
}