【问题标题】:C# Method AttributesC# 方法属性
【发布时间】:2015-08-25 06:39:13
【问题描述】:

有没有办法在不注入的情况下实现这一点?主题是一个用户控件。我正在尝试检查标题并将其设置在属性中。

public partial class Topic: TopicBase
{
[Topic(Title = "My Topic")]
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
}

当我在 TopicBase.cs 中查找属性时,我得到 null

protected override void OnInit(EventArgs e)
    {
        var topicAttr = Attribute.GetCustomAttribute(this.GetType(), typeof(TopicAttribute)); //topicAttr is null here.
        if (topicAttr != null)
        {
            SetTopic(((TopicAttribute)topicAttr).Title);
        }
    }

【问题讨论】:

    标签: c# reflection custom-attributes


    【解决方案1】:

    您正在检查 type 上的属性。您的属性位于 方法 上。更改您的查询或将属性放在查询所期望的类型上:

    [Topic(Title = "My Topic")]
    public partial class Topic : TopicBase
    {
    }
    

    【讨论】:

    • 查询方法应该是什么?
    • 使用您的方法的 MemberInfo 调用 same method 应该可以工作。
    • 谢谢。但是当我尝试 Type clsType = typeof(Topic); MethodInfo mInfo = clsType.GetMethod("OnInit"); //mInfo 再次为空。
    【解决方案2】:

    正如 nvoigt 所说,您正在尝试查找类的属性,但您应该使用方法的 MemberInfo。

    类似的东西:

    MethodInfo methodInfo = typeof(Topic).GetMethod("OnInit", BindingFlags.NonPublic | BindingFlags.Instance);
    var attribute = methodInfo.GetCustomAttribute(typeof(TopicAttribute));
    

    【讨论】:

    • 你需要使用this.GetType()而不是typeof(Topic),因为OP想要检查派生类方法。
    • @nvoigt,哦,你说得对,我只是没有意识到第二种方法是在父类中,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2018-10-17
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多