C# 方法属性

C# Method Attributes

有没有不用注入的方法?主题是一个 UserControl。我正在尝试检查标题并将其设置在属性中。

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);
        }
    }

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

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

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

类似的东西:

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