You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin访问SQLite数据库报错:对象引用未设置为实例

解决Xamarin SQLite连接空引用错误

核心问题:接口名称不匹配

你报错代码里调用的是DependencyService.Get<ISQLiteInterface>(),但你定义的接口是ISQLiteConnection,接口名称完全不一致,导致DependencyService.Get返回null,后续调用.GetSQLiteConnection()就会触发“对象引用未设置为对象的实例”错误。

修正步骤

  1. 统一接口名称
    将报错代码里的ISQLiteInterface改为ISQLiteConnection:

    _SQLiteConnection = DependencyService.Get<ISQLiteConnection>().GetSQLiteConnection();
    
  2. 检查实现类的Dependency特性
    确认你的Droid实现类上的[assembly: Dependency(typeof(GetSQLiteConnnection))]特性放在命名空间之外(当前代码是正确的),且GetSQLiteConnnection类确实完整实现了ISQLiteConnection接口。

  3. 修正SQLiteConnection构造的命名空间
    你实现类的方法返回类型是SQLite.Net.SQLiteConnection,但构造实例时写的是SQLiteConnection,可能存在命名空间冲突,建议加上完整命名空间:

    var connection = new SQLite.Net.SQLiteConnection(platform, path);
    
  4. 验证SQLite NuGet包引用
    确保共享项目和Droid项目都安装了匹配版本的SQLite相关NuGet包(比如SQLite.Net-PCL),避免因缺少依赖导致实例化失败。

  5. 确认Xamarin.Forms初始化
    在Android项目的MainActivity的OnCreate方法中,确保已完成Xamarin.Forms初始化:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }
    

额外排查点

  • 检查实现类的命名空间SqliteLoginDemo.Droid.Dependencies是否被正确编译,确保Droid项目能识别到该类。
  • 可以先判断服务是否获取成功,避免直接调用方法触发空引用:
    var sqliteService = DependencyService.Get<ISQLiteConnection>();
    if (sqliteService != null)
    {
        _SQLiteConnection = sqliteService.GetSQLiteConnection();
    }
    else
    {
        // 处理服务未找到的异常情况
    }
    

内容的提问来源于stack exchange,提问作者user22408554

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 06:16:06