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

时间:2015-10-11 18:07:48

标签: c# reflection uwp

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

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

1 个答案:

答案 0 :(得分:31)

针对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类是其中之一,对于COM类型的反射很困难。微软无法掩盖两者之间的巨大差异,不得不创建TypeInfo 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 Output窗口的内容:

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