c# - 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();
};
解决方案
实现接口不是从类继承。这就是为什么此类属性不会从接口传播到类的原因。请参阅:bradwilson.typepad.com/blog/2011/08/interface-attributes-class-attributes.html
但是有一些解决方法:C# 类可以从其接口继承属性吗?
推荐阅读
- android - 使用 Canvas 和 Bitmap 在特定坐标处绘制多个图像
- java - java.lang.IllegalArgumentException:API 密钥不能为空
- java - 如何在 RestAssured 的正文中发送带有表单数据的 POST,并设置具有特定内容类型的多部分
- javascript - 如何读取子组件中的当前 React.useRef?
- r - 如何可视化 R 中箱线图中的特定数据点?
- user-interface - 如何在搪瓷网格容器中设置固定宽度/高度
- azure-data-factory - Azure DataFactory 清理:删除所有对象
- google-colaboratory - 有没有办法在 google colab 中使用网络摄像头捕捉实时视频?
- elasticsearch - 关于联合查询的问题?
- php - 如何在php中将字符串转换为数组