我希望这个类使用懒加载的单例模式
时间: 2023-08-02 18:07:26 浏览: 43
好的,我根据你的需求,对上面的代码进行了修改,实现了懒加载的单例模式,代码如下:
```csharp
using System;
using System.IO;
namespace ProjectManager
{
public sealed class ProjectManager
{
private static readonly Lazy<ProjectManager> lazyInstance = new Lazy<ProjectManager>(() => new ProjectManager());
private ProjectManager()
{
// 私有构造函数
}
public static ProjectManager Instance
{
get { return lazyInstance.Value; }
}
readonly string projectPath = "Project"; // 项目文件夹路径
public void PrintProjectNames()
{
// 查询当前的所有项目名称
Console.WriteLine("所有项目名称:");
string[] projectNames = GetProjectNames();
foreach (string projectName in projectNames)
{
Console.WriteLine(projectName);
}
}
public void ReplaceProject(string projectName)
{
// 替换某一个项目到当前项目
string sourcePath = Path.Combine(projectPath, projectName, "PeiZhi");
string destinationPath = "根目录";
Directory.CreateDirectory(destinationPath); // 如果根目录不存在,则创建
DirectoryCopy(sourcePath, destinationPath, true);
}
public void RenameProject(string oldName, string newName)
{
// 根据某一个项目的名称,更改该项目的名称
string oldPath = Path.Combine(projectPath, oldName);
string newPath = Path.Combine(projectPath, newName);
Directory.Move(oldPath, newPath);
}
// 查询当前的所有项目名称
private string[] GetProjectNames()
{
string[] projectFolders = Directory.GetDirectories(projectPath);
string[] projectNames = new string[projectFolders.Length];
for (int i = 0; i < projectFolders.Length; i++)
{
projectNames[i] = Path.GetFileName(projectFolders[i]);
}
return projectNames;
}
// 文件夹复制方法
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// 如果目标文件夹不存在,则创建
Directory.CreateDirectory(destDirName);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, true);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string tempPath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
}
}
}
}
}
```
这个类现在是一个单例类,通过`ProjectManager.Instance`可以获取唯一的实例。在构造函数中,我们不再需要查询所有项目名称,而是把这个方法放到了`PrintProjectNames()`方法中,这样在第一次调用`PrintProjectNames()`方法时才会查询所有项目名称,实现了懒加载。其他两个方法也做了相应的修改。