所以这是我第一次问这里,请耐心等待。 我正在尝试学习如何将属性附加到我的对象,但我无法检索它们。 所以这是我的属性类:
[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个对象。所以我不确定发生了什么事?
提前致谢。