xamarin 文件系统,当前,OpenAppPackageFileAsync与文件系统,OpenAppPackageFileAsync

wko9yo5t  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(278)

为什么其他人需要使用Current(如版本A中)?

// Version A
using var stream = await FileSystem.Current.OpenAppPackageFileAsync("monkeys.json");

// Version B
using var stream = await FileSystem.OpenAppPackageFileAsync("monkeys.json");

以下是详细信息:

public interface IFileSystem
{
    string CacheDirectory { get; }
    string AppDataDirectory { get; }

    Task<bool> AppPackageFileExistsAsync(string filename);
    Task<Stream> OpenAppPackageFileAsync(string filename);
}

public static class FileSystem
{
    public static string CacheDirectory { get; }

    public static string AppDataDirectory { get; }
    public static IFileSystem Current { get; }

    public static Task<bool> AppPackageFileExistsAsync(string filename);

    public static Task<Stream> OpenAppPackageFileAsync(string filename);
}
wb1gzix0

wb1gzix01#

这可能是这里发生的历史遗留下来的一点。历史上,Xamarin.Essentials没有(很好的)对依赖注入的支持。
对于.NET MAUI,我们确实添加了这一点,但是,我们也希望确保不使用依赖注入的人仍然可以按照他们喜欢的方式使用它。这就是为什么所有Essentials API现在都有一个可以访问的CurrentDefault静态示例,以及可以用于依赖注入的接口版本。
在这种具体情况下,差异为零,参见下文中撰写本文时的source of FileSystem(省略不相关代码):

public static class FileSystem
{
    public static Task<Stream> OpenAppPackageFileAsync(string filename)
        => Current.OpenAppPackageFileAsync(filename);

    public static Task<bool> AppPackageFileExistsAsync(string filename)
        => Current.AppPackageFileExistsAsync(filename);

    static IFileSystem? currentImplementation;

    public static IFileSystem Current =>
        currentImplementation ??= new FileSystemImplementation();

    internal static void SetCurrent(IFileSystem? implementation) =>
        currentImplementation = implementation;
}

在这里,您可以看到FileSystem.OpenAppPackageFileAsync只是调用了Current.OpenAppPackageFileAsync的underneat

相关问题