找到实现接口

时间:2015-12-21 14:49:34

标签: c# reflection properties interface-implementation

所以,我有一个解决方案,用于获得具体类时的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属性与Base类proprety定义相匹配?

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

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

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

上的文档