1

所以这是我第一次在这里问,请多多包涵。我正在尝试学习如何将属性附加到我的对象,但我无法检索它们。所以这是我的属性类:

[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 个对象。所以我不确定发生了什么?

提前致谢。

4

0 回答 0