C# 获取接口属性的运行时getter

C# 获取接口属性的运行时getter,c#,reflection,C#,Reflection,声明: interface I { int i { get; set; } } class C : I { public int i { get; set; } } 代码: 嘿,v1==v2,pi1!=pi2,但显然调用了相同的方法。我如何在代码中知道pi1和pi2调用同一个方法体?您可以使用它来获取特定类型的接口成员和实现成员之间的映射。下面是一个例子: using System; using System.Linq; using System.Threading; in

声明:

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

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

嘿,
v1==v2
pi1!=pi2
,但显然调用了相同的方法。我如何在代码中知道
pi1
pi2
调用同一个方法体?

您可以使用它来获取特定类型的接口成员和实现成员之间的映射。下面是一个例子:

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

。。。然后它将打印
实现是classGetter吗?错误

只是猜测而已。您是否尝试过:
pi1.DeclaringType==pi2.DeclaringType&&pi1.Name==pi2.Name
?@itsme86
DeclaringType
不同:
I
C
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}");
            }
        }
    }
}
interface I
{
    int Value { get; set; }
}

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

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