处理操作系统特定操作的聪明方法?(Windowsl/Linux)

ttisahbt  于 2023-02-03  发布在  Linux
关注(0)|答案(1)|浏览(170)

我目前正在用.NET6开发我的第一个跨平台应用程序,它应该可以在windows和linux上运行。我已经达到了拥有第一个稳定且可以工作的项目的程度。现在我不想再做一些重构,特别是代码进行一些操作系统特定操作的部分。目前,a用一个简单的if/else来解决这个问题,比如

if (OperatingSystem.IsLinux())
{
    path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
}
else
{
    path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
}

我正在寻找一个好方法来避免这些if/else语句,并创建一些“更干净”的代码。我的想法是有一个类,如OSSpecificActions,并为每个用例创建一个函数。如:

public class OperatingSystemSpecificAction
{
internal static string PathToDefaultFolder()
    {
        string path = String.Empty;

        if (OperatingSystem.IsLinux())
        {

            path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        }
        else
        {
            path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        }
        return path;
    }
}

在我的代码中这样调用它:

path = OperatingSystemSpecificAction.PathToDefaultFolder();
ruarlubt

ruarlubt1#

您可以使用DI容器来设置依赖项的正确版本,然后将它们注入到应用程序的其余部分,
例如,在启动时:

if (OperatingSystem.IsLinux()) 
{
    services.AddTransient<IPathResolver, LinuxPathResolver>();
}
else 
{
    services.AddTransient<IPathResolver, WindowsPathResolver>();
}

那么在你的消费类中:

public class ConsumingClass
{
    public ConsumingClass(IPathResolver pathResolver)
    {
       var correctPath = pathResolver.GetFolderPath()
    }
}

类的两个实现将执行特定于操作系统的逻辑。这比创建一个充满“特定于操作系统的操作”的大类更好地扩展。

相关问题