gpt4 book ai didi

c# - C#中的多个构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:15 24 4
gpt4 key购买 nike

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

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

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

    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[] 的私有(private)方法作为参数,比如说 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.");
}

关于c# - C#中的多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14814154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com