0

したがって、具象クラスがあるときに 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。具象クラスのプロパティに属性があるため、それらを取得する必要があります。

どんな助けでも大歓迎です!

4

1 に答える 1