C# PropertyInfo GetCustomAttributes返回0个对象

C# PropertyInfo GetCustomAttributes返回0个对象,c#,attributes,propertyinfo,C#,Attributes,Propertyinfo,所以这是我第一次在这里问,请容忍我。 我正在尝试学习如何将属性附加到对象,但检索它们时遇到了困难。 这是我的属性类: [AttributeUsage(AttributeTargets.Property)] public class attr : System.Attribute { public readonly Boolean Required; public string formID { get; set; } public attr(Boolean requi

所以这是我第一次在这里问,请容忍我。 我正在尝试学习如何将属性附加到对象,但检索它们时遇到了困难。 这是我的属性类:

[AttributeUsage(AttributeTargets.Property)]
public class attr : System.Attribute
{
    public readonly Boolean Required;

    public string formID { get; set; }

    public attr(Boolean required)
    {
        this.Required = required;
    }

    public attr(Boolean required, string formID)
    {
        this.Required = required;
        this.formID = formID;
    }
}
我如何将其“附加”到某个对象上的属性的示例:

public class MyObject
{
    [attr(true, "formRequireField")]
    public int RequiredField { get { return REQUIREDFIELD; } set { REQUIREDFIELD = value; } }
}
以及当前如何检索属性的代码:

foreach (PropertyInfo property in typeof(MyObject).GetProperties())
{
    Attribute[] attributes = Attribute.GetCustomAttributes(property, false);
    foreach (Attribute attribute in attributes)
    {
        if (attribute is attr)
        {
            attr propAttr = (attr)attribute;
            if (propAttr.Required)
            {
                Page.Form.FindControl(propAttr.formID);
            }
        }
    }
我也尝试过这种格式

    object[] attributes = property.GetCustomAttributes(true);
    foreach (object attribute in attributes)
    {
        if (attribute is attr)
        {
            attr propAttr = (attr)attribute;
            if (propAttr.Required)
            {
                Page.Form.FindControl(propAttr.formID);
            }
        }
    }
}
它们都返回0个对象。所以我不确定到底发生了什么


提前谢谢。

我无法复制此内容-您提供的样品对我来说很好。如果遵循正常的.NET命名约定,代码将更易于阅读。你可以发布一个简短但完整的程序,但实际上失败了吗?很抱歉让它很难阅读,但这已经是我想做的要点,我唯一可以添加更多的是,这段代码在一个Page_LoadComplete事件处理程序中。我只想能够访问我的类的属性。所以我还没有“完整”的节目要展示。我想知道这是否是一个双重声明的问题;是否存在
属性.Length
非零的情况?我不知道它是否存在,但作为一种不同的形式如果你问的是,如果可能有其他代码块使用它并“重新分配”它,那么没有,这是我仅有的一个甚至使用反射类的代码块。@Jesse:好吧,我接受了你给出的代码,并从中创建了一个完整的程序,只做了很小的修改——它工作了。你应该把你在这里付出的与你真正得到的相比较。例如,您的属性在这里是公共的-在您的真实代码中是公共的吗?