c# - 如何检索类属性的属性值?
问题描述
是否可以从 c# 中的自定义属性类中检索公共成员。考虑以下属性类:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class ModuleMessageHandlerAttribute : Attribute
{
public Type type { get; set; }
public ModuleMessageHandlerAttribute(Type type)
{
this.type = type;
}
}
我有一些使用此属性的处理程序类如下:
[ModuleMessageHandler(typeof(HelloModule))]
public class HelloMessageHandler : IMessageHandler<Hello>
{
}
接下来,我需要访问ModuleMessageHandlerAttribute类的 Type 属性,以比较 Type 是否与特定类匹配。
解决方案
你的意思是这样的:
[ModuleMessageHandler(typeof(SomeType))]
class SomeClass
{
void SomeMethod()
{
ModuleMessageHandlerAttribute attribute = GetType()
.GetCustomAttribute<ModuleMessageHandlerAttribute>();
Type type = attribute.type;
}
}
推荐阅读
- django - Django 静态文件未正确加载
- bash - 仅从多个文件中提取 LUFS
- python-3.x - 如何访问 Meta 类中的类常量?
- java - 解压缩使用 java.util.zip.Inflater 编码的 gzip base64
- python - 由于二进制文件的签名无效且二进制文件未签名,因此无法公证 .pkg 文件
- uber-api - 如何从 Uber SDK android 和 iOS 获取请求的乘车详情?
- node.js - “anymatch”的完整性检查失败(计算的完整性与我们的记录不匹配,得到
- android-jetpack-compose - 如何在 Jetpack Compose 中预览 LazyPagingItems/Paging 3 库
- python - Python API json 文件到 Jupyter 中的 Pandas 数据框
- python - SQLAlchemy 的多对多插入如何工作?