简体   繁体   中英

GetCustomAttribute with multiple instance of XmlArrayItemAttribute

I have a List<TransformationItem> . TransformationItem is just base class for multiple classes, such as ExtractTextTransform and InsertTextTransform

In order to use built-in XML Serialization and Deserialization, I have to use multiple instance of XmlArrayItemAttribute , as described in http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute%28v=vs.80%29.aspx

You can apply multiple instances of the XmlArrayItemAttribute or XmlElementAttribute to specify types of objects that can be inserted into the array.

Here is my code:

[XmlArrayItem(Type = typeof(Transformations.EvaluateExpressionTransform))]
[XmlArrayItem(Type = typeof(Transformations.ExtractTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.InsertTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.MapTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.ReplaceTextTransform))]
[XmlArrayItem(Type = typeof(Transformations.TextItem))]
[XmlArrayItem(ElementName = "Transformation")]
public List<Transformations.TransformationItem> transformations;

The problem is, when I use reflection to get ElementName attribute with GetCustomAttribute() , I got AmbiguousMatchException .

How can I solve this, say, get the ElementName ?

As more than one attribute was found, you need to use ICustomAttributeProvider.GetCustomAttributes() . Otherwise, the Attribute.GetCustomAttribute() method throws an AmbiguousMatchException , as it doesn't know which attribute to select.

I like to wrap this as an extension method, eg:

public static IEnumerable<TAttribute> GetAttributes<TAttribute>(this ICustomAttributeProvider provider, bool inherit = false)
    where TAttribute : Attribute
{
    return provider
        .GetCustomAttributes(typeof(TAttribute), inherit)
        .Cast<TAttribute>();
}

Called like:

var attribute = typeof(TransformationItem)
    .GetAttributes<XmlArrayItemAttribute>(true)
    .Where(attr => !string.IsNullOrEmpty(attr.ElementName))
    .FirstOrDefault();

if (attribute != null)
{
    string elementName = attribute.ElementName;
    // Do stuff...
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM