Xamarin项目Device.OnPlatform过时警告咨询:需替换为Switch(RuntimePlatform)
解决Xamarin中
Device.OnPlatform过时警告的方案 嘿,我之前维护老旧Xamarin项目的时候也碰到过这个警告,改起来其实挺简单的,官方推荐的switch写法比原来的OnPlatform更直观,咱们一步步来搞定它!
首先得明白为啥会出这个警告:Xamarin.Forms从2.3.4版本开始就弃用了泛型的Device.OnPlatform<T>方法,这种写法在多平台适配时灵活性不足,而且后续版本的API规划里也不再维护它了,换成基于Device.RuntimePlatform的switch语句是最优解。
原来的过时代码示例
假设你原来的代码是这样的:
using System; using System.Collections.Generic; using Xamarin.Forms; // ... 其他业务代码 var margin = Device.OnPlatform( iOS: new Thickness(20, 40, 20, 20), Android: new Thickness(16, 24, 16, 16), WinPhone: new Thickness(12, 16, 12, 12) );
修改后的基础版本代码
用switch语句替换掉原来的OnPlatform调用,既符合新API规范,又能消除警告:
using System; using System.Collections.Generic; using Xamarin.Forms; // ... 其他业务代码 Thickness margin; switch (Device.RuntimePlatform) { case Device.iOS: margin = new Thickness(20, 40, 20, 20); break; case Device.Android: margin = new Thickness(16, 24, 16, 16); break; case Device.WinPhone: case Device.UWP: // 如果项目兼容UWP,记得加上这个分支 margin = new Thickness(12, 16, 12, 12); break; default: // 给个默认值,避免出现"并非所有代码路径都返回值"的编译警告 margin = new Thickness(16); break; }
更简洁的写法(C# 8.0+支持)
如果你的项目已经升级到支持C# 8.0及以上版本,还可以用更简洁的switch表达式写法:
var margin = Device.RuntimePlatform switch { Device.iOS => new Thickness(20, 40, 20, 20), Device.Android => new Thickness(16, 24, 16, 16), Device.WinPhone or Device.UWP => new Thickness(12, 16, 12, 12), _ => new Thickness(16) };
额外小技巧:统一封装减少重复代码
如果项目里有很多地方都用到了平台适配逻辑,可以封装一个静态工具类,不用每次都写switch:
public static class PlatformUtils { public static T GetPlatformValue<T>(T iosValue, T androidValue, T fallbackValue) { return Device.RuntimePlatform switch { Device.iOS => iosValue, Device.Android => androidValue, _ => fallbackValue }; } // 扩展支持WinPhone/UWP的重载 public static T GetPlatformValue<T>(T iosValue, T androidValue, T winPhoneValue, T fallbackValue) { return Device.RuntimePlatform switch { Device.iOS => iosValue, Device.Android => androidValue, Device.WinPhone or Device.UWP => winPhoneValue, _ => fallbackValue }; } }
之后调用就很省心:
var margin = PlatformUtils.GetPlatformValue( new Thickness(20, 40, 20, 20), new Thickness(16, 24, 16, 16), new Thickness(12, 16, 12, 12), new Thickness(16) );
这样改完之后,那个过时警告就会消失,代码也更符合Xamarin后续版本的规范,以后项目升级也会更顺利~
内容的提问来源于stack exchange,提问作者Marcelo Rachado
相关产品推荐
相关产品推荐

