ASP.NET对象是否可以获取其属性

时间:2009-05-14 01:49:01

标签: c# .net attributes

考虑以下自定义属性:

[Abc.Text(MaxLength=33)]
public Abc.Text heading = new Abc.Text();

MaxLength在TextAtrribute类中定义:

public class TextAttribute : Attribute
{
  public int MaxLength {get; set;}

}

在其他代码中,Text类需要知道它的MaxLength。

有没有办法可以做到这样的事情:

int max = (int)heading.GetAttribute("MaxLength");

对答案的评论

RexM答案的这种修改起了作用:

System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.TextAttribute), true);

if (attribs.Length == 1)
{
  int max = ((Abc.TextAttribute)attribs[0]).AbcMaxLength;
}

但是我希望我能够在没有引用该领域的父母“this”的情况下做到这一点。 你能以某种方式得到一个领域的父母吗?这样可以解决它,例如

System.Reflection.FieldInfo headingField = heading.GetParent().GetType().GetField("heading");

2 个答案:

答案 0 :(得分:3)

在当前对象的类型上使用GetCustomAttributes()方法。这将返回一个对象数组,表示该类型属性的实例,这些属性属于您指定的属性类型:

object[] attribs = this.GetType().GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

编辑:好的,通过你的澄清,我理解你想要做的更好一些。我想我第一次误读了你的代码示例。它本质上是相同的概念,但属性是在一个字段上,而不是类:

System.Reflection.FieldInfo headingField = this.GetType().GetField("heading");
object[] attribs = headingField.GetCustomAttributes(typeof(Abc.Text));
if (attribs.Length == 1)
{
    int max = ((Abc.Text)attribs[0]).MaxLength;
}

再次编辑:为了获得该字段的句柄,您必须知道该字段所在的类型。一种简单的方法是使用this.GetType(),但您也可以执行以下操作:

FieldInfo headingField = typeof(MyClass).GetField("heading");

答案 1 :(得分:-1)

您可以阅读here如何做您想做的事。

Type type = TextAttribute.GetType();
PropertieInfo pi = type.GetProperty("MaxLength");
if (pi.CanRead())
  //the value
  pi.GetValue();
相关问题