Search code examples
c#reflectionwindows-8windows-runtime

How to get Type from TypeInfo in WinRT?


I want to register all my view models for serialization, by convention.

However the following code will not compile because the var viewmodel in the foreach loop is of type TypeInfo:

protected override void OnRegisterKnownTypesForSerialization()
{
    var viewModels = this.GetType().GetTypeInfo().Assembly.DefinedTypes
            .Where(t => _viewModelNameRegex.IsMatch(t.FullName))
            .ToList();

    foreach (var viewmodel in viewModels)
    {
        SessionStateService.RegisterKnownType(viewmodel);
    }
}

Apparently TypeInfo does not inherit from Type:

public abstract class TypeInfo : MemberInfo, IReflectableType

Unlike the full featured version, which does inherit from Type.

So how can I get to Type from a WinRT TypeInfo?


Solution

  • TypeInfo inherits from Type in the standard .NET library, but in the portable library it is declared as:

    public abstract class TypeInfo : MemberInfo, IReflectableType
    

    The function AsType() returns the closest thing to the traditional Type

    public virtual Type AsType()
    

    Which returns Type weakly related to the TypeInfo above

    public abstract class Type