从自定义属性访问父类

时间:2010-06-06 14:22:14

标签: c# asp.net asp.net-mvc

是否可以从属性中访问父类。

例如,我想创建一个DropDownListAttribute,它可以应用于MVC中viewmodel类的属性,然后从编辑器模板创建一个下拉列表。我遵循与Kazi Manzur Ra​​shid here类似的路线。

他将类别集合添加到viewdata中,并使用提供给属性的密钥检索它们。

我想做类似下面的事情,

public ExampleDropDownViewModel {

   public IEnumerable<SelectListItem> Categories {get;set;}

   [DropDownList("Categories")]
   public int CategoryID { get;set; }
}

该属性采用包含要绑定的集合的属性的名称。我无法弄清楚如何访问属性的父类的属性。有谁知道怎么做?

由于

2 个答案:

答案 0 :(得分:1)

你可以使用反射来做到这一点。在主要课程中执行以下操作:

Type type = typeof(ExampleDropDownViewModel));
// Get properties of your data class
PropertyInfo[] propertyInfo = type.GetProperties( );

foreach( PropertyInfo prop in propertyInfo )
{
   // Fetch custom attributes applied to a property        
   object[] attributes = prop.GetCustomAttributes(true);

   foreach (Attribute attribute in attributes) {
      // we are only interested in DropDownList Attributes..
      if (attribute is DropDownListAttribute) {
    DropDownListAttribute dropdownAttrib = (DropDownListAttribute)attribute;
         Console.WriteLine("table set in attribute: " + dropdownAttrib.myTable);
      }
   }
}

答案 1 :(得分:1)

您无法从属性访问父类型。属性是应用于类型的元数据,但您无法回顾并尝试识别类型,除非您执行以下操作:

[MyCustomAttribute(typeof(MyClass))]
public class MyClass {
  ///
}

使用上面的反射解决方案,您实际上并没有实现从属性获取类型的操作,而是反过来,您从类型获取属性。此时,您已经拥有了类型。

相关问题