繁体   English   中英

C#中的多个构造函数

[英]multiple constructors in C#

我有需要数据的类,它可以是字节或文件路径。

此刻,我将文件读入字节数组,然后设置类。 在另一个分隔符中,它直接根据作为参数传递的字节来设置类。

我希望第一个构造函数(文件路径)调用第二个(字节),类似于:

    public DImage(byte[] filebytes) : this()
    {
        MemoryStream filestream = null;
        BinaryReader binReader = null;
        if (filebytes != null && filebytes.Length > 0)
        {
            using (filestream = new MemoryStream(filebytes))
            {
                if (filestream != null && filestream.Length > 0 && filestream.CanSeek == true)
                {
                    //do stuff
                }
                else
                    throw new Exception(@"Couldn't read file from disk.");
            }
        }
        else
            throw new Exception(@"Couldn't read file from disk.");
    }


    public DImage(string strFileName) : this()
    {
        // make sure the file exists
        if (System.IO.File.Exists(strFileName) == true)
        {
            this.strFileName = strFileName;
            byte[] filebytes = null;
            // load the file as an array of bytes
            filebytes = System.IO.File.ReadAllBytes(this.strFileName);
            //somehow call the other constructor like
            DImage(filebytes);                         
        }
        else
           throw new Exception(@"Couldn't find file '" + strFileName);

    }

那么如何从第二个调用第一个构造函数(以保存复制和粘贴代码)呢?

您可以创建一个以byte[]作为参数的私有方法,例如ProcessImage(byte[] myparam) ,这两个构造函数都将调用该方法来处理您的字节。

旁注:您可能要考虑使用stream而不是byte[]


快速示例:

public DImage(byte[] filebytes) : this()    // Remove if no parameterless constructor
{
    MemoryStream filestream = null;
    BinaryReader binReader = null;
    if (filebytes != null && filebytes.Length > 0)
    {
        using (filestream = new MemoryStream(filebytes))
        {
            this.ProcessStream(filestream);
        }
    }
    else
        throw new Exception(@"Couldn't read file from disk.");
}

public DImage(Stream stream) : this()   // Remove if no parameterless constructor
{
    this.ProcessStream(stream);
}    

public DImage(string strFileName) : this()  // Remove if no parameterless constructor
{
    // make sure the file exists
    if (System.IO.File.Exists(strFileName) == true)
    {
        this.strFileName = strFileName;

        // process stream from file
        this.ProcessStream(System.IO.File.Open(strFileName));
    }
    else
       throw new Exception(@"Couldn't find file '" + strFileName);
}

...

private ProcessStream(Stream myStream)
{
    if (filestream != null && filestream.Length > 0 && filestream.CanSeek == true)
    {
        //do stuff
    }
    else
        throw new Exception(@"Couldn't read file from disk.");
}

我实际上建议公开两个静态方法:

public static DImage FromFile(string filename)
{
    // Load image, then call constructor
}

public static DImage FromData(byte[] data)
{
    // Do anything you need to, then call the constructor
}

构造函数的确切形式由您决定,但我可能会将其设为私有。 根据我的经验,使用静态工厂方法可以使代码更清晰,这意味着您可以推迟调用实际的构造函数,直到您准备好实际工作为止。 这有助于将字段设置为只读等。最大的缺点是缺少对继承的支持。

我可以想象实现3个构造函数:

  1. 接受可以由System.IO.StreamReader访问的System.Stream
  2. 接受一个字节数组,将其包装到System.IO.MemoryStream并调用第一个构造函数。
  3. 接受文件名,使用System.IO.FileStream加载它并调用第一个构造函数。

这是一个例子:

using System.IO;

// ...

public DImage(Stream Stream)
{
    using (var reader = new StreamReader(Stream))
    {
        // Read the image.
    }
}

public DImage(byte[] Bytes) 
    : this(new MemoryStream(Bytes))
{
}

public DImage(string FileName) 
    : this(new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
}

这也使处理异常更加容易。 如果该文件不存在,则FileStream的构造方法将抛出System.IO.FileNotFoundException ,因此无论您在实例化DImage类的DImage位置,都可以对其进行处理:

try
{
    var image = new DImage(@"C:\Test.img");
}
catch (System.IO.FileNotFoundException e)
{
    // The image could not be found.
}
catch (Exception e)
{
    // Something else happened.
}

此方法在构造函数后面使用关键字this来将特殊构造案例委托给默认构造函数。 它有两个优点:

  1. 通过消除代码重复来减少所需的代码。
  2. 通过定义默认构造函数并接受System.Stream提高可重用性。 客户端可以调用构造函数从内存块或文件系统条目中加载图像,也可以实现自己的流以提供自定义数据源(如DB BLOB,NetworkStreams等)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM