正在查找实现接口的正确属性

本文关键字:属性 实现 查找 接口 | 更新日期: 2023-09-27 18:27:46

因此,我认为我有一个解决方案,可以在拥有具体类时获得PropertyInfo,并为该具体类实现的接口获得PropertyInfo。这是代码:

public static PropertyInfo GetImplementingProperty(Type concreteType, PropertyInfo interfaceProperty)
        {
            // do some region parameter check, skipped
            var interfaceType = interfaceProperty.DeclaringType;
            //use the set method if we have a write only property
            var getCorrectMethod = interfaceProperty.GetGetMethod() == null
                ? (Func<PropertyInfo, MethodInfo>) (p => p.GetSetMethod(true))
                : p => p.GetGetMethod(true);
            var propertyMethod = getCorrectMethod(interfaceProperty);
            var mapping = concreteType.GetInterfaceMap(interfaceType);
            MethodInfo targetMethod = null;
            for (var i = 0; i < mapping.InterfaceMethods.Length; i++)
            {
                if (mapping.InterfaceMethods[i] == propertyMethod)
                {
                    targetMethod = mapping.TargetMethods[i];
                    break;
                }
            }
            foreach (var property in concreteType.GetProperties(
                BindingFlags.Instance | BindingFlags.GetProperty |
                BindingFlags.Public | BindingFlags.NonPublic)) // include non-public!
            {
                if (targetMethod == getCorrectMethod(property)) // include non-public!
                {
                    return property;
                }
            }
            throw new InvalidOperationException("The property {0} defined on the interface {1} has not been found on the class {2}. That should never happen."
                .FormatText(interfaceProperty.Name, interfaceProperty.DeclaringType.FullName, concreteType.FullName));
        }

不幸的是,我发现了一个失败的案例,我不确定如何解决这个问题。所以我在dll中有一个类:

public abstract class BaseClass
{
    public Guid ConfigId { get; set; }
    public virtual Guid ConfigId2 { get; set; }
}

然后在另一个dll中我做:

    interface INamed
    {
        Guid ConfigId { get; }
        Guid ConfigId2 { get; }
    }
    private class SuperClass : BaseClass, INamed
    {
    }

现在

        ReflectionHelper.GetImplementingProperty(typeof(SuperClass), typeof(INamed).GetProperty("ConfigId2")); // this works
        ReflectionHelper.GetImplementingProperty(typeof(SuperClass), typeof(INamed).GetProperty("ConfigId")); // this fails

知道如何将ConfigId属性与基类属性定义相匹配吗?

PS。我有关于具体类属性的属性,这就是为什么我需要得到这些属性。

感谢您的帮助!

正在查找实现接口的正确属性

您需要将BindingFlags.FlattenHierarchy添加到GetProperties调用中才能获得父类属性。请参阅上的文档https://msdn.microsoft.com/en-us/library/kyaxdd3x(v=vs.110).aspx