【问题标题】:What is [assembly: Dependency()] in Xamarin?Xamarin 中的 [程序集:Dependency()] 是什么?
【发布时间】:2020-03-29 00:05:28
【问题描述】:

我是 Xamarin 的新手。我正在关注一个教程,并且在那个

[assembly: Dependency(typeof())]

被使用了。我不明白这行代码的作用是什么。 请解释一下它的功能。

以下是代码。

[assembly: Dependency(typeof(SQLiteAndroid))]

namespace XamTestThree.Droid.Data {
    public class SQLiteAndroid :ISQLite{
        public SQLiteAndroid() { }
        public SQLite.SQLiteConnection GetConnection()
        {
            var sqlLiteFileName = "TestDB.db3";
            string documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentPath, sqlLiteFileName);
            var conn = new SQLite.SQLiteConnection(path);
            return conn; 

        }
    }
}

【问题讨论】:

    标签: c# android .net xamarin xamarin.forms


    【解决方案1】:

    这称为注册。

    平台实现必须向DependencyService 注册,以便Xamarin.Forms 可以在运行时找到它们。

    这通常使用DependencyAttribute 执行,这表明指定的类型提供了interface 的实现。

    欲了解更多信息,请访问DependencyServices - Microsoft docs.

    【讨论】:

      【解决方案2】:

      这是一个依赖属性。

      DependencyAttribute 可用于向DependencyService 注册平台实现。该属性表示指定的类型提供了接口的具体实现。

      以下示例展示了使用 DependencyAttribute 注册 IDeviceOrientationService 接口的 iOS 实现:

      using Xamarin.Forms;
      
      [assembly: Dependency(typeof(DeviceOrientationService))]
      namespace DependencyServiceDemos.iOS
      {
          public class DeviceOrientationService : IDeviceOrientationService
          {
              public DeviceOrientation GetOrientation()
              {
                  ...
              }
          }
      }
      

      如需更多文档,请查看official docs

      【讨论】:

        【解决方案3】:

        在我的情况下,这一行显示此错误:

        **cannot convert from 'System.Type' to 'System.Runtime.CompilerServices.LoadHint'**
        `[assembly: DefaultDependency(typeof(SQLite_Android))]`
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-07
          • 2013-03-02
          • 2015-01-14
          • 2012-04-15
          • 1970-01-01
          • 1970-01-01
          • 2011-05-25
          • 1970-01-01
          相关资源
          最近更新 更多