代码之家  ›  专栏  ›  技术社区  ›  madcapnmckay

从自定义属性访问父类

  •  3
  • madcapnmckay  · 技术社区  · 15 年前

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

    here .

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

    我想做下面这样的事,

    public ExampleDropDownViewModel {
    
       public IEnumerable<SelectListItem> Categories {get;set;}
    
       [DropDownList("Categories")]
       public int CategoryID { get;set; }
    }
    

    该属性采用包含要绑定到的集合的属性的名称。我不知道如何访问属性的父类上的属性。有人知道怎么做吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Matthew Abbott    15 年前

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

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

        2
  •  1
  •   S P    15 年前

    你可以通过反射来实现。在你的主课上做以下练习:

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