首页 > 解决方案 > 如何检索类属性的属性值?

问题描述

是否可以从 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 是否与特定类匹配。

标签: c#.net-core

解决方案


你的意思是这样的:

[ModuleMessageHandler(typeof(SomeType))]
class SomeClass
{
    void SomeMethod()
    {
        ModuleMessageHandlerAttribute attribute = GetType()
            .GetCustomAttribute<ModuleMessageHandlerAttribute>();
        Type type = attribute.type;
    }
}

推荐阅读