首页 > 解决方案 > C#反射获取接口属性的实现属性

问题描述

我有一个接口,我在属性上定义了一个自定义属性,我想从该接口的派生实例中检索相关属性。

public interface ITopicProcessor<T>
{
    [TopicKey]
    string TopicName { get; }

    [OtherAttribute]
    string OtherProperty { get; }

    void Process(T message);
}

public class MyClassProcessor : ITopicProcessor<MyClass>
{
    public string TopicName => "MyTopic";

    public string OtherProperty => "Irrelevant";

    public void Process(MyClass message)
    {
    }
}

我可以接近以下内容 - 主要问题是派生接口类型似乎没有与泛型类型定义相同的自定义属性。我很确定这部分是由于需要使用底层方法实现而不是直接使用属性值

// iType is typeof(ITopicProcessor<MyClass>)
// I also have access to the generic type definition if need be - i.e. typeof(ITopicProcessor<>)
Func<Type, string> subscriberTypeToTopicKeySelector = iType =>
{
    // Creating an instance via a dependency injection framework
    var instance = kernel.Get(iType);
    var classType = instance.GetType();

    var interfaceMap = classType.GetInterfaceMap(iType);
    // interfaceMap.InterfaceMethods contains underlying get_property method, but no custom attributes
    var interfaceMethod = interfaceMap.InterfaceMethods
                                      .Where(x => x.HasAttribute<TopicKeyAttribute>())
                                      .ToList();
    var classMethodInfo = interfaceMap.TargetMethods[Array.IndexOf(interfaceMap.InterfaceMethods, interfaceMethod)];

    return classMethodInfo.Invoke(instance, BindingFlags.Default, null, null, CultureInfo.CurrentCulture)
                          .ToString();
};

标签: c#reflection

解决方案


实现接口不是从类继承。这就是为什么此类属性不会从接口传播到类的原因。请参阅:bradwilson.typepad.com/blog/2011/08/interface-attributes-class-attributes.html

但是有一些解决方法:C# 类可以从其接口继承属性吗?


推荐阅读