Type t = obj.GetType();
t.IsEnum;
t.IsPrimitive;
t.IsGenericType
t.IsPublic;
t.IsNestedPublic
t.BaseType
t.IsValueType
在UWP中,以上所有属性都不存在。现在我该如何检查这些类型?
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类就是其中之一,Reflection用于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);
}
此代码的VS输出窗口内容:
False
False
False
True
False
System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
False
Windows.Foundation.Metadata
命名空间中的类和方法。例如Windows.Foundation.Metadata.ApiInformation.IsMethodPresent
。 - Raymond ChenApiInformation.IsEventPresent
,然后是ApiInformation.IsMethodPresent
,再然后是ApiInformation.IsPropertyPresent
,直到某个返回true
。不确定如何从 C# 中获取到IInspectable.GetRuntimeClassName
。虽然一般来说,你的代码应该知道它拥有什么,而不是通过反射来确定。即使你使用了反射,你会怎么做呢?“耶,我知道这是一个枚举。”那又怎样呢?你不知道枚举的值代表什么。 - Raymond Chen