.net-maui - .NET MAUI 中的部分平台特定方法

标签 .net-maui partial-classes platform-specific

我正在尝试在 .NET MAUI 中实现平台特定的部分方法以获取数据库的连接字符串。

在“主应用程序”中:

namespace TestApp.DL;

public partial class BaseHandler
{
    public partial string GetDBPath();

    private string GetCnnPath() 
    {
        var dbPath = GetDBPath();
        var cnnPath = $"Data Source={dbPath}";

        return cnnPath;
    }

    ...
}

在项目的平台文件夹中:

enter image description here

其中每个都包含平台特定的实现:

namespace TestApp.DL;

// All the code in this file is only included on Android.
public partial class BaseHandler
{
    public string GetDBPath()
    {
        var dbName = "com.mycompany.mydatabase.db";
        return Android.App.Application.Context.GetDatabasePath(dbName).AbsolutePath;
    }
}

...但我不断收到“错误 CS8795:分部方法‘BaseHandler.GetDBPath()’必须具有实现部分,因为它具有可访问性修饰符。(CS8795)”。编译器似乎看不到特定于平台的文件?请注意,它们与主应用程序位于一个单独的程序集项目中,但我想这应该没问题,因为 fwk 为我创建了文件夹?

最佳答案

当您与分部斗争时,您可以继续使用分部类,但避免使用分部方法。在创建 maui 库时尤其如此,如果这种方法容易出错,而在 maui 应用程序中编译工作正常。

“快速修复解决方案”,所有分部类显然必须使用相同的命名空间:

共享代码,无论您使用什么,您都希望将 NET6_0 更改为 NET7_0:

public partial class BaseHandler
{
    private string GetCnnPath() 
    {
        var dbPath = GetDBPath();
        var cnnPath = $"Data Source={dbPath}";

        return cnnPath;
    }

#if (NET6_0 && !ANDROID && !IOS && !MACCATALYST && !WINDOWS && !TIZEN)

        public string GetDBPath()
        {
            throw new PlatformNotSupportedException();
        }
#endif
}

您在平台 Platforms/Android 中的特定于平台的代码:

public partial class BaseHandler
{
    public string GetDBPath()
    {
        var dbName = "com.mycompany.mydatabase.db";
        return Android.App.Application.Context.GetDatabasePath(dbName).AbsolutePath;
    }
}

关于.net-maui - .NET MAUI 中的部分平台特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010644/

相关文章:

c# - 向实体添加新的构造函数

design-patterns - 我该如何重构这个不幸的部分类?

c# - 指南 - 扩展方法与部分类

c++ - node-gyp 平台特定插件

swift - 将数据从flutter传递到原生IOS

drop-down-menu - 下拉菜单适用于 Mac 浏览器,但不适用于 PC

xaml - 状态栏主题仅在重新启动应用程序后更改

c# - 在两个内容页面之间传递数据;

ios - 无法更改 IOS 上的 .NET MAUI Blazor 启动屏幕