在 Xamarin 中拆分 class 定义

split class definitions in Xamarin

我正在用 xamarin 开发跨平台应用程序。我想在我的共享库中定义多个 类,然后使用每个平台的平台特定代码来实现它们。这些 类 将在我的主视图模型中引用以控制不同的功能(例如电池电量、wifi、usb 摄像头)。执行此操作的最佳方法是什么?

在 Xamarin 中,您可以使用接口来完成此操作。在使用接口的 C# 中,您定义了一个契约,任何实现它的 class 都必须满足该契约。

使用您的示例,假设您的共享文件夹中有一个名为 IBatteryService 的界面。

public interface IBatteryService
{
     double GetBatteryLevel();
}

您将在每个平台项目中实现此接口的三个实现:iOS、Android 和 UWP。这些实现将具有特定于平台的代码来获取您正在寻找的内容。

public class BatteryServiceIOS : IBatteryService
{
    public double GetBatteryLevel()
    {
        ///
        /// iOS code to get the device battery level
        ///

        return batteryLevel;
    }
}

您的 ViewModel 将使用使代码不知道正在使用哪个实现的接口。

public class HomeViewModel
{
    IBatteryService _batteryLevel;

    public HomeViewModel()
    {
        //You will initialize your instance either using DI (Dependency Injection or by using ServiceLocator.
    }

    public double GetDeviceBatteryLevel()
    {
         // At this moment the VM doesn't know which implementation is used and it actually doesn't care.
         return _batteryLevel.GetBatteryLevel();
    }
}

在您的应用组合根中,借助 iOC 将定义将要使用的实现。每个平台都将注册它自己的实现。然后在您的 ViewModel 中,您将通过使用 ServiceLocator 注入或获取已注册的实现。

通常这是 Xamarin 插件的工作方式。您可以查看 github.

中的 DeviceInfo 插件代码

这是一个很好的教程,它详细解释了 C# IoC

希望这已经够清楚了。