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

时间:2016-02-17 15:41:42

标签: c# class defensive-copy

我有以下课程:

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);
        }
    }

我有另一个类将folderagent作为构造函数中的参数,这是创建Folderagent对象的防御副本的正确方法吗?

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;
        }
    }

1 个答案:

答案 0 :(得分:0)

你基本上想要一个数组所有元素的副本。请注意,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);
}