Reflection in universal windows platform (UWP) missing properties

前端 未结 1 1568
醉酒成梦
醉酒成梦 2021-02-02 13:53
Type t = obj.GetType();
t.IsEnum;
t.IsPrimitive;
t.IsGenericType
t.IsPublic;
t.IsNestedPublic
t.BaseType
t.IsValueType

All of the above properties are

相关标签:
1条回答
  • 2021-02-02 14:27

    A C# app that targets UWP uses two distinct sets of types. You already know the .NET types, like System.String, but the UWP specific types are actually COM interfaces under the hood. COM is the super-glue of interop, the basic reason why you can also write UWP apps in Javascript and C++. And C#, WinRT is an unmanaged api at its core.

    The language projection for WinRT built into the .NET Framework makes that nasty little detail highly invisible. Some WinRT types are easy to identify, anything in the Windows namespace for example. Some can be both, a System.String can be both a .NET type and wrap a WinRT HSTRING. The .NET Framework automagically figures this out by itself.

    Very invisible, but there are some cracks in the spackle. The Type class is one of them, Reflection for COM types is difficult. Microsoft could not hide the big difference between the two and had to create the TypeInfo class.

    You'll find all the missing properties back in that class. Some silly sample code that shows it at work in a UWP app:

    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);
        }
    

    Content of the VS Output window for this code:

    False
    False
    False
    True
    False
    System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
    False
    
    0 讨论(0)
提交回复
热议问题