开发者

Access parent class from custom attribute

Is it possible to access a parent class from within an attribute.

For example I would like to create a DropDownListAttribute which can be applied to a property of a viewmodel class in MVC and then create a drop down list from an editor template. I am following a similar line as Kazi Manzur Rashid here.

He adds the collection of categories into viewdata and retrieves them using the key supplied to the attribute.

I would like to do something like the below,

public ExampleDropDownViewModel {

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

   [DropDownList("Categories")]
   public int CategoryID { get;set; }
}开发者_StackOverflow社区

The attribute takes the name of the property containing the collection to bind to. I can't figure out how to access a property on the parent class of the attribute. Does anyone know how to do this?

Thanks


You can't access a parent type from an attribute. Attributes are metadata that is applied to a type, but you can't look back and try and identify the type, unless you did something like:

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

With the reflection solution above, you are not actually achieving the action of getting a type from an attribute, you are doing the reverse, you are getting attributes from a type. At this point, you already have the type.


You can do that using reflection. Do the following in your main class:

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);
      }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜