通用Windows平台(UWP)缺少属性的反射

Mat*_*att 16 c# reflection uwp

Type t = obj.GetType();
t.IsEnum;
t.IsPrimitive;
t.IsGenericType
t.IsPublic;
t.IsNestedPublic
t.BaseType
t.IsValueType
Run Code Online (Sandbox Code Playgroud)

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

Han*_*ant 31

针对UWP的AC#app使用两组不同的类型.您已经知道.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类是其中之一,对于COM类型的反射很困难.微软无法隐藏两者之间的巨大差异,不得不创建TypeInfo类.

您将在该课程中找到所有缺失的属性.一些愚蠢的示例代码在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);
    }
Run Code Online (Sandbox Code Playgroud)

此代码的VS Output窗口的内容:

False
False
False
True
False
System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
False
Run Code Online (Sandbox Code Playgroud)