Get the getter property of an interface interface

Ads:

interface I
{
    int i { get; set; }
}

class C : I
{
    public int i { get; set; }
}

the code:

C c = new C();
c.i = 10;
PropertyInfo pi1 =
    c.
    GetType().
    GetInterfaces().
    SelectMany(t => t.GetProperties()).
    ToArray()[0];
PropertyInfo pi2 =
    c.
    GetType().
    GetProperties()[0];
object v1 = pi1.GetValue(c);
object v2 = pi2.GetValue(c);

Hey v1 == v2, pi1 != pi2but GetValueclearly it refers to the same method. How do I know in my code, that pi1and pi2causes the same method body?

+4
source share
1 answer

You can use Type.GetInterfaceMap()to get a mapping between interface members and implementing members for a particular type. Here is an example:

using System;
using System.Linq;
using System.Threading;

interface I
{
    int Value { get; set; }
}

class C : I
{
    public int Value { get; set; }
}

public class Test
{
    static void Main()
    {
        var interfaceGetter = typeof(I).GetProperty("Value").GetMethod;
        var classGetter = typeof(C).GetProperty("Value").GetMethod;
        var interfaceMapping = typeof(C).GetInterfaceMap(typeof(I));

        var interfaceMethods = interfaceMapping.InterfaceMethods;
        var targetMethods = interfaceMapping.TargetMethods;
        for (int i = 0; i < interfaceMethods.Length; i++)
        {
            if (interfaceMethods[i] == interfaceGetter)
            {
                var targetMethod = targetMethods[i];
                Console.WriteLine($"Implementation is classGetter? {targetMethod == classGetter}");
            }
        }
    }
}

What prints Implementation is classGetter? True- but if you change the code so that the selection I.Valuedoes not call C.Value, for example. adding a base class so that it C.Valueis a new property, not an implementation I.Value:

interface I
{
    int Value { get; set; }
}

class Foo : I
{
    public int Value { get; set; }
}

class C : Foo
{
    public int Value { get; set; }
}

... then he will print Implementation is classGetter? False.

+4

Source: https://habr.com/ru/post/1671659/


All Articles