创建自定义类防御性副本的正确方法

本文关键字:方法 副本 自定义 防御性 创建 | 更新日期: 2023-09-27 18:35:07

我有以下类:

public class FolderAgent
    {
        public string directoryName {get; private set; }
        public int numberofdirectories {get; private set; }
        public int numberofFiles {get; private set;}
        public DirectoryInfo [] directories {get; private set;}
        public FileInfo [] files {get; private set;}
        public FolderAgent(string directoryName, int numberofdirectories, int numberofFiles, DirectoryInfo [] listDir, FileInfo [] listFiles)
        {
            this.directoryName = directoryName;
            this.numberofdirectories = numberofdirectories;
            this.numberofFiles = numberofFiles;
            Array.Copy(listDir, directories, listDir.Length);
            Array.Copy(listFiles, files, listFiles.Length);
        }
    }

我还有另一个类,它将文件夹代理作为构造函数中的参数,这是创建文件夹代理对象的防御性副本的正确方法吗?

public class FolderKey
    {
        public FolderAgent folder {get; private set;}
        public int returnValue {get; private set;}
        public FolderKey(FolderAgent folder, int returnValue)
        {
            this.folder = new FolderAgent(folder.directoryName, folder.numberofdirectories, folder.numberofFiles, folder.directories, folder.files);
            this.returnValue = returnValue;
        }
    }

创建自定义类防御性副本的正确方法

你基本上想要数组所有元素的副本。请注意,FileInfoDirectoryInfo使用缓存数据,这些数据在您第一次访问任何文件/目录属性时初始化。

因此,您也可以重新创建对象,而不是复制...类似(未经测试):

public FolderAgent(string directoryName, int numberofdirectories,
                   int numberofFiles, DirectoryInfo [] listDir, 
                   FileInfo [] listFiles)
{
    this.directoryName = directoryName;
    this.numberofdirectories = numberofdirectories;
    this.numberofFiles = numberofFiles;
    directories = new DirectoryInfo[listDir.length];
    for(var i = 0; i < listDir.length; i++)
      directories[i] = new DirectoryInfo(listDir[i].FullName);
    files = new FileInfo[listFiles.length];
    for(var i = 0; i < listFiles.length; i++)
      files[i] = new FileInfo(listFiles[i].FullName);
}