C# 如何知道执行代码的当前操作系统/平台(Android / iOS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18570878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know the current OS / platform of the executing code (Android / iOS)
提问by Askolein
Using Xamarin.Android and Xamarin.iOS, I need to now the current OS in a shared code section. Be it an enum, an int or a string, it doesn't matter.
使用 Xamarin.Android 和 Xamarin.iOS,我现在需要共享代码部分中的当前操作系统。无论是枚举、整数还是字符串,都没有关系。
I tried this:
我试过这个:
System.Environment.OSVersion
Which is always "Unix" with some kernel version informations.
它总是带有一些内核版本信息的“Unix”。
There are info on Android for example like
有关于 Android 的信息,例如
Android.OS.Build.VERSION
But it needs to be in the Android specific code section. Is there any way of knowing the current OS in a common library?
但它需要在 Android 特定的代码部分。有没有办法知道公共库中的当前操作系统?
采纳答案by maulik sakhare
You can also try this and its probably the best solution I found :
你也可以试试这个,它可能是我找到的最好的解决方案:
if(Device.RuntimePlatform == Device.iOS)
{
//iOS stuff
}
else if(Device.RuntimePlatform == Device.Android)
{
}
回答by Stephane Delcroix
Using reflection, try to retrieve the value of the Monotouch.Version
property (and the equivalent for MfA: Android.OS.Build.VERSION). One of the calls will fail, the other should succeed; that's why you have to use reflection. That's for a real runtime check.
使用反射,尝试检索Monotouch.Version
属性的值(以及 MfA 的等效项:Android.OS.Build.VERSION)。一个调用会失败,另一个应该成功;这就是为什么你必须使用反射。这是真正的运行时检查。
But as your app is compiled twice, you can fix that value at compile time.
但是当您的应用程序编译两次时,您可以在编译时修复该值。
#if MONOTOUCH
var platform = "iOS"
#else
var platform = "Android"
#endif
回答by jzeferino
I'm using DeviceInfoplugin.
It supports Android, iOs, Windows Phone Silverlight, Windows Phone RT, Windows Store RT, Windows 10 UWP
and it works perfectly.
我正在使用DeviceInfo插件。它支持Android, iOs, Windows Phone Silverlight, Windows Phone RT, Windows Store RT, Windows 10 UWP
并且完美运行。
It can be used in PCL
like this (you must add the plugin to the platform projects and to PCL
):
它可以PCL
像这样使用(您必须将插件添加到平台项目和到PCL
):
var platform = CrossDeviceInfo.Current.Platform;
switch(platform){
case Platform.iOS:
// iOS
break;
case Platform.Android:
// Android
break;
}
This kind of code isn't a good practice in PCL
, its better to use Dependency Injection
(this plugin use that) to customize platform specific behaviour.
这种代码在 中不是一个好的做法PCL
,最好使用Dependency Injection
(这个插件使用那个)来自定义平台特定的行为。