在PCL中在运行时检测通用应用程序 [英] Detect Universal App at Runtime in PCL

查看:244
本文介绍了在PCL中在运行时检测通用应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测主应用程序是来自便携式类库的通用应用程序(W10)?

Is there any way to detect that a main application is a Universal App (W10) from a Portable Class Library?

感谢

推荐答案

开箱即用我不认为您要求的功能在PCL中可用,但这里是一个涉及反思的建议,您可能想要试试。

Out-of-the-box I do not think the functionality you are asking for is available in PCL, but here is a suggestion involving reflection that you might want to try.

它适用于您正在使用的PCL配置文件(328),涉及.NET 4和Silverlight 5. GetPlatformName 方法需要稍微调整,如果你想例如切换到PCL简档111和259,因为这些简档将不得不依赖 TypeInfo 而不是 Type

It is adapted to the PCL Profile (328) you are using, involving .NET 4 and Silverlight 5. The GetPlatformName method needs to be somewhat adjusted if you want to for example switch to PCL profiles 111 and 259, since these profiles would have to rely on TypeInfo rather than Type.

这里是建议的方法和附带的接口,可以在便携式类库中实现:

Here is the proposed method and accompanying interface, which can be implemented in the Portable Class Library:

public static class RuntimeEnvironment
{
    public static string GetPlatformName()
    {
        var callingAssembly = (Assembly)typeof(Assembly).GetMethod("GetCallingAssembly").Invoke(null, new object[0]);
        var type = callingAssembly.GetTypes().Single(t => typeof(IPlatform).IsAssignableFrom(t));
        var instance = (IPlatform)Activator.CreateInstance(type);
        return instance.PlatformName;
    }
}

public interface IPlatform
{
    string PlatformName { get; }
}

除了上述代码,您还需要实现 IPlatform 在每个平台特定应用程序中的界面,例如像这样:

Apart from the above code, you will also need to implement the IPlatform interface in each platform-specific application, for example like this:

public class UniversalPlatform : IPlatform
{
    public string PlatformName => "UWP";
}

简而言之, GetPlatformName 方法实例化在调用(应用程序)程序集中实现 IPlatform 接口的单个​​类,并返回 PlatformName 属性

In short, the GetPlatformName method instantiates the single class implementing the IPlatform interface in the calling (application) assembly, and returns the PlatformName property.

Assembly.GetCallingAssembly 方法未在任何PCL配置文件中公开显示,

The Assembly.GetCallingAssembly method is not publicly exposed in any of the PCL profiles, but it is generally implemented and can therefore be accessed via reflection.

GetPlatformName 方法是完全可移植的,因此可以在便携式类库本身,允许您在PCL代码中进行平台条件决策。该建议确实需要在每个平台特定的应用程序中的最小代码努力,因为你需要实现 IPlatform ,但也许这是一个可以接受的价格支付?

The GetPlatformName method is fully portable and can thus be consumed within the Portable Class Library itself, allowing you to make platform conditional decisions within the PCL code. The proposal does require minimal code efforts within each platform-specific application, since you do need to implement IPlatform, but maybe that is an acceptable price to pay?

这篇关于在PCL中在运行时检测通用应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆