我正在尝试在 .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;
}
...
}
在项目的平台文件夹中:
其中每个都包含平台特定的实现:
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/