有时候须要在不一样的平台上,运行不一样的代码,下面就看是说明这个需求怎么实现。ui
在共享的目录中处理逻辑spa
在Xamarin.Forms
中,有这些指令能够使用:#if, #elif, and endif.
来看一下代码code
#if __IOS__ using UIKit; #elif __ANDROID__ using Android.OS; #elif WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_UWP using Windows.Security.ExchangeActiveSyncProvisioning; #endif
这就是一个完整的体系,这些指令不止做用于开头,类里面也是能够使用的。orm
若是要实如今不一样平台调用不一样平台的类,则须要在每一个平台的工程上都要新建一个共同类,类名、方法和命名空间,要彻底一致。接口
Xamarin Formsstring
PlatformInfo platformInfo = new PlatformInfo();
IOSit
using System; using UIKit; namespace PlatInfoSap2 { public class PlatformInfo { UIDevice device = new UIDevice(); public string GetModel() { return device.Model.ToString(); } public string GetVersion() { return String.Format("{0} {1}", device.SystemName, device.SystemVersion); } } }
Androidio
using System; using Android.OS; namespace PlatInfoSap2 { public class PlatformInfo { public string GetModel() { return String.Format("{0} {1}", Build.Manufacturer, Build.Model); } public string GetVersion() { return Build.VERSION.Release.ToString(); } } }
一个库一般不能访问应用程序项目中的类,那么咱们是能够使用DependencyService
类来调用,各个平台的方法。form
怎么作?class
1.在Xamarin Forms
平台上建立一个接口,让各个平台来实现该接口
2.每一个平台实现了该接口后,必须注册在Dependency
属性上
3.在Xamarin Forms
中,使用DependencyService
类的Get
方法就能够调用了
代码
IPlatformInfo platformInfo = DependencyService.Get<IPlatformInfo>(); modelLabel.Text = platformInfo.GetModel(); versionLabel.Text = platformInfo.GetVersion();