Skip to content

IDynamicInterfaceCastable and reflection #37787

@MichalStrehovsky

Description

@MichalStrehovsky

Some reflection problems are unsolvable for IDynamicInterfaceCastable (e.g. having GetInterfaces return the dynamic list of interfaces), but reflection APIs that deal with castability should be solvable:

using System;
using System.Runtime.InteropServices;

interface IFoo
{
    void Frob();
}

[DynamicInterfaceCastableImplementation]
interface IFooImpl : IFoo
{
    void IFoo.Frob() => Internal.Console.WriteLine("Hello");
}

class Program :  IDynamicInterfaceCastable
{
    public bool IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented)
    {
        return true;
    }

    public RuntimeTypeHandle GetInterfaceImplementation(RuntimeTypeHandle interfaceType)
    {
        return typeof(IFooImpl).TypeHandle;
    }

    public static void Greet(IFoo f) => f.Frob();

    static void Main()
    {
        // Returns false
        Internal.Console.WriteLine(typeof(IFoo).IsAssignableFrom(typeof(Program)).ToString());

        // Throws that the interface is not implemented
        var m = typeof(Program).GetInterfaceMap(typeof(IFoo));
        for (int i = 0; i <= m.InterfaceMethods.Length; i++)
            Internal.Console.WriteLine($"{m.InterfaceMethods[i]}: {m.TargetMethods[i]}");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions