Inside a class, I have the following piece of code:
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType))]
[System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType))]
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
Using just reflection, is it possible to retrieve these attributes?
I saw 'GetCustomAttributes() on the respective Type, but didnt get much joy.
You need to retrieve the attributes from the property, not the type itself, like so:
typeof(MyClass).GetProperty("Items").GetCustomAttributes(typeof(XmlElementAttribute), false);
Or more complete (remember to import System.Linq for Cast<> and ToArray() to work):
XmlElementAttribute[] attribs = typeof(TheType)
.GetProperty("Items")
.GetCustomAttributes(typeof(XmlElementAttribute), false)
.Cast<XmlElementAttribute>()
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With