代码之家  ›  专栏  ›  技术社区  ›  Dan TheCodeJunkie

在类实例的属性上查找属性

  •  0
  • Dan TheCodeJunkie  · 技术社区  · 16 年前

    给定一个类的实例,我想在运行时设置属性的属性。

    所以我尝试了这个方法,但据我所知,这个方法在类上查找属性,而不是实例,所以我对属性属性所做的任何更改都没有效果。

    var properties = myObject.GetType().GetProperties();
    
    foreach (object prop in properties)
    {
       var attribute =prop.GetCustomAttributes(typeof(MyAttribute), true)[0];
       //attribute.MyProp do some stuff
    }
    

    如果我尝试使用下面这样的类型描述符,就无法获得属性上的属性。

    var myObject= (MyClass) object;
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myObject);
    
    //There is no props[0].GetCustomAttributes(
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   Matthew Abbott    16 年前

    属性是应用于类型或类型成员(而不是实例)的元数据。如果要对类的特定实例应用值,是否应考虑使用属性/字段?