How do you get to the attributes?



  • I have Type Attribute. I know. Assembly The type that has the right attribute.

    types = ass.GetTypes().Where(t => t.CustomAttributes.Any(a => a.AttributeType == utilTypes[1]));
    

    I mean, I get a list of types. I need to get the attributes of the attributes of the atribut by changing this list. Like this one.

    [MyAttribute("Hello")]
    class MyClass{}
    

    I need to get my properties. Prop1whichever "Hello."♪ How do you do that? Something's messed up in these reflexes:

    UPD1

    I forgot to say. I don't have direct access to the type of attribute. I mean, I can't do that.

    foreach (var type in types)
    {
        var MyAttr = (MyAttributeAttribute)type.GetCustomAttribute(utilTypes[0].GetType())
    }
    

    Because that's the type of attribute. MyAttributeAttribute I only have text. Which means I need to get some way out of it that I don't have direct access to.



  • Try the next approach.
    Have a copy of the class MyClass lies in the variable. type♪ I mean:

    Type type = typeof(MyClass);
    

    Or in your case:

    Type type = types[i];
    

    Then the following code:

    var attr = type.CustomAttributes.FirstOrDefault(a => a.AttributeType == utilTypes[0]);
    if (attr != null)
    {
        var attrType = attr.AttributeType;
        var propInfo = attrType.GetProperty("Prop1", BindingFlags.Instance | BindingFlags.Public);
        Console.WriteLine(propInfo.GetValue(mcType.GetCustomAttribute(attrType)));
    }
    

    He'll find out:

    Hello.


    Here's the method:

    public static object GetAttributeProperty(Type classType, Type attributeType, string propertyName)
    {
        var propInfo = attributeType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
        return propInfo.GetValue(classType.GetCustomAttribute(attributeType));
    }
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2