反映通用 windows 平台 (UWP) 缺少的属性

Reflection in universal windows platform (UWP) missing properties

Type t = obj.GetType();
t.IsEnum;
t.IsPrimitive;
t.IsGenericType
t.IsPublic;
t.IsNestedPublic
t.BaseType
t.IsValueType

UWP 中缺少上述所有属性。我现在如何检查这些类型?

以 UWP 为目标的 C# 应用使用两组不同的类型。您已经知道 .NET 类型,例如 System.String,但 UWP 特定类型实际上是幕后的 COM 接口。 COM 是互操作的超级粘合剂,这是您还可以使用 Javascript 和 C++ 编写 UWP 应用程序的基本原因。和 C# 一样,WinRT 的核心是非托管 api。

.NET Framework 中内置的用于 WinRT 的 语言投影 使那些讨厌的小细节变得非常不可见。某些 WinRT 类型很容易识别,例如 Windows 命名空间中的任何类型。有些可以是两者,System.String 可以既是 .NET 类型又可以包装 WinRT HSTRING。 .NET Framework 会自动解决这个问题。

非常不可见,但在散布上有一些裂缝。 Type class 就是其中之一,COM 类型的反射很困难。微软无法隐藏两者之间的巨大差异,不得不创建 TypeInfo class.

您会在 class 中找到所有缺失的属性。一些愚蠢的示例代码显示它在 UWP 应用程序中的工作:

using System.Reflection;
using System.Diagnostics;
...

    public App()
    {
        Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
            Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
            Microsoft.ApplicationInsights.WindowsCollectors.Session);
        this.InitializeComponent();
        this.Suspending += OnSuspending;
        // Reflection code...
        var t = typeof(string).GetTypeInfo();
        Debug.WriteLine(t.IsEnum);
        Debug.WriteLine(t.IsPrimitive);
        Debug.WriteLine(t.IsGenericType);
        Debug.WriteLine(t.IsPublic);
        Debug.WriteLine(t.IsNestedPublic);
        Debug.WriteLine(t.BaseType.AssemblyQualifiedName);
        Debug.WriteLine(t.IsValueType);
    }

此代码的 VS 输出内容 window:

False
False
False
True
False
System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
False