【问题标题】:Reflection in universal windows platform (UWP) missing properties通用 Windows 平台 (UWP) 中的反射缺少属性
【发布时间】:2016-01-09 04:18:30
【问题描述】:
Type t = obj.GetType();
t.IsEnum;
t.IsPrimitive;
t.IsGenericType
t.IsPublic;
t.IsNestedPublic
t.BaseType
t.IsValueType

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

【问题讨论】:

  • 使用Windows.Foundation.Metadata命名空间中的类和方法。例如。 Windows.Foundation.Metadata.ApiInformation.IsMethodPresent.
  • @RaymondChen 感谢您的指点,但我将如何检查上述属性?唯一可用的方法是检查方法、事件、属性和类型是否存在。
  • 如果你有一个类型名但你不知道它是什么,我猜你可以调用ApiInformation.IsEventPresent,然后是ApiInformation.IsMethodPresent,然后是ApiInformation.IsPropertyPresent,以此类推,直到返回true。不知道如何从 C# 获取 IInspectable.GetRuntimeClassName。虽然一般来说,你的代码应该知道它有什么,而不是试图通过反射来确定。即使你有反思,你会怎么做? “是的,我知道这是一个枚举。”所以呢?你不知道枚举的值是什么意思。

标签: c# reflection uwp


【解决方案1】:

面向 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 会自动自己解决这个问题。

非常不可见,但在 spackle 中有一些裂缝。 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 输出窗口的内容:

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

【讨论】:

  • 感谢您的详细回复。这将为我指明正确的方向。
猜你喜欢
  • 2014-05-24
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多